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?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
Why don't you use composition instead? Have your class keep a reference to the desired object, and delegate to it.
One path is to use the 'mixin' approach:
Another way is the composition:
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:
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 lineto
create another base class implementing this one method and make class2 and class1 both inherit this class