Chris Mueller
Chris Mueller

Reputation: 6680

Defining subclasses with common import methods

I have been building a python image processing module for working with images related to laser beams. The images differ in their content (laser beam image, scattered light image, etc.) and the file types differ based on the instrument used to capture the images. But any one of the file types may contain any one of the content types.

The structure of the module currently is

The issue is that the grandchildren classes are essentially identical because they contain code for importing different types of files which may contain content from either child class.

Is there a more elegant/pythonic way to do this?


I should note that the different file types require different pre-processing, so the solution is not as simple as using e.g. PIL which can recognize the standard image file extensions.

Upvotes: 1

Views: 57

Answers (1)

DevLounge
DevLounge

Reputation: 8437

Use 2 mixin classes:

class FileTypeAMixin:
    <logic>

class FileTypeBMixin:
    <logic>

class Parent:
    <logic>

class Child1(Parent):
    <logic>

class Child2(Parent):
    <logic>

class Child1GrandChild1(FileTypeAMixin, Child1):
    <logic>

class Child1GrandChild2(FileTypeBMixin, Child1):
    <logic>

class Child2GrandChild1(FileTypeAMixin, Child2):
    <logic>

class Child2GrandChild2(FileTypeBMixin, Child2):
    <logic>

EDIT As pointed out by the OP, it is recommended to always put the mixins before the parent classes, in order to prevent strange MRO behavior when calling super() in case each of the parent classes/mixins have the same methods implemented.

Upvotes: 1

Related Questions