Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do partial inheritance with Python?

Tags:

I'm creating a class (class0) in Python that is a currently based off of one class (class1); however, I'd like to inherit from another class as well (class2). The thing about class2 is that I don't want all of it's methods and attributes, I just need one single method. Is it possible for class0 to only inherit a single method form a class2?

like image 287
rectangletangle Avatar asked Apr 13 '11 09:04

rectangletangle


People also ask

Which inheritance is not possible in Python?

Answer: Unlike other object-oriented programming languages like Java, Python supports all types of inheritance, even multiple inheritance!

Does Python allow multi level inheritance?

A class can be derived from more than one base class in Python, similar to C++. This is called multiple inheritance. In multiple inheritance, the features of all the base classes are inherited into the derived class.

How do Python achieve multiple inheritance?

if class C inherits from P then all the sub-classes of C would also inherit from P. When a class is derived from more than one base class it is called multiple Inheritance. The derived class inherits all the features of the base case.


2 Answers

The "mixin" method of having another class that just implemetns the method you want is the correct thing to do in this case. But for sake of completeness, as it answers exactly what you are asking, I add that yes, it is possible to have a behavior just like the "partial inheritance" you want (but note that such a concept does not exist formally).

All one have to do is to add member on the new class that refer to to the method or attribute you wish to repeat there:

class Class2(object):    def method(self):       print ("I am method at %s" % self.__class__)  class Class1(object):    pass  class Class0(Class1):    method = Class2.__dict__["method"]  ob = Class0() ob.method() 

Note that retrieving the method from the class __dict__ is needed in Python 2.x (up to 2.7) - due to runtime transforms that are made to convert the function in a method. In Python 3.0 and above, just change the line

method = Class2.__dict__["method"] 

to

method = Class2.method 
like image 59
jsbueno Avatar answered Sep 30 '22 06:09

jsbueno


One path is to use the 'mixin' approach:

class Mixin(object):     def method(self):         pass  class C1(Mixin, ...parents...):     pass  class C2(Mixin, ...parents...):     pass 

Another way is the composition:

class C1(object):     def method(self):         pass  class C2(object):     def __init__(self):         self.c1 = C1()      def method(self):         return self.c1.method() 
like image 25
zindel Avatar answered Sep 30 '22 06:09

zindel