Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
843 views
in Technique[技术] by (71.8m points)

class - Is it possible to do partial inheritance with Python?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...