I need to extend the parent classes of two child classes by adding shared methods to them. Starting with the initial definitions of the child classes:
class ChildA(ParentA): pass class ChildB(ParentB): pass
The parent classes behave similarly but their implementations are different, thus each child class must inherit separately from them. For example,
ParentA has behavior that when destroyed terminates the program, but
ParentB does not. However, the parent classes have attributes that both child classes would need to perform operations on. There are 5 methods I need to add, that both child classes use regularly. I could define each method in the child classes but the code is identical and thus redundant. From this I believe a "mixin" class would serve well:
class Mixin: def some_method(self): self.my_attribute.do_something() # my_attribute exists in ParentA and Parent B class ChildA(ParentA, Mixin): pass class ChildB(ParentB, Mixin): pass
I've never done this, and it appears to me that I may be violating some rule by having a class defining methods that use attributes of a class that inherits from itself. This dependency could cause undefined behavior if somebody where to use the
Mixin class for another child class that does not also inherit from a parent class that makes these attributes available.
Is there a way to secure this approach? Is this the best approach? Is there a name for this type of class design/inheritance? Am I breaking any major design rules/principles?