0

In Python there is the possibility of using inheritance to obtain different classes after one parent. But is it possible that I have various "child" classes that have the same methods that strictly depends on the parent class, and that each one inherits a different parent, like the following example

class Parent_1():
    methods for parent 1

class Parent_2():
    methods for parent 2

class Parent_3():
    methods for parent 3

GENERAL_CHILD_METHODS -> is an object that includes all the methods that all the childs will share

class Child_1(inherits Parent_1 and uses GENERAL CHILD METHODS)

class Child_2(inherits Parent_2 and uses GENERAL CHILD METHODS)

class Child_3(inherits Parent_3 and uses GENERAL CHILD METHODS)
     

is it possible to create something like the GENERAL_CHILD_METHOD object that I mention in the example? so that I do not have to copy all the same methods for each child, because in the end they are the same. So I suppose there is a way to wrap this methods so that I only have to use one line to call all of them in each Child class and not to have to copy everything all the time.

  • 4
    Maybe you want all three parents to inherit from a single class, but the question is abstract enough that it's hard to say; a mix-in might also be appropriate. (See [Mixins vs inheritance](https://stackoverflow.com/questions/860245/mixin-vs-inheritance) for background on mixins; also, [What is a mix-in and why is it useful?](https://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-is-it-useful)) – Charles Duffy Jan 13 '23 at 18:41
  • 2
    Python has multiple inheritance, so `class Child_3(Parent_3, Child):` will work with a `Child` class defining methods. As others have said, a mixin may be better, but hard to say with the info. – Mark Jan 13 '23 at 18:46
  • Mmm, and would that work if the Child functionality depends obligatorily of the existence of the parent? like, it cannot work without the inheritance of the parent. – Juan Esteban Agudelo Ortiz Jan 13 '23 at 18:47
  • 1
    There are multiple inheritance trees you could use, depending on what you mean by "work": All three Child_* classes could inherit from GenChild. All three parents could inherit from GenParent. GenChild might or might not inherit from GenParent - or GenChild might be structured so that it won't function without _some_ GenParent subclass. It's a mixin, it doesn't have to be functional on its own. See also Charles Duffy's links above. – Sarah Messer Jan 13 '23 at 18:50

0 Answers0