Non-Virtual Inheritance in Python
Is non-virtual inheritance possible in Python, or do I have to use composition?
I would like to call methods against an individual instance of the base class for each subclass rather than a single one for all subclasses.
Update Example:
- Class A has an list in it.
- Class B and C are sublasses of A
- B and C add things to A's list.
- B and C's items are both in a single list in a single A object.
- I want B and C to have there own A, and hence their own A开发者_运维问答.list.
In Python, there is no separate instance of a base class if the base class is inherited multiple times. I don't believe it's possible to achieve what you're asking using inheritance. Composition should work fine though.
P.S. Your question is phrased in a rather cryptic manner (using C++ terminology for a purely Python question), but I think I understood it. If I didn't, my apologies.
B and C can have their own list instances, but you must explicitly say so in the body of these classes. Consider this example:
class A(object):
collection = [1, 2, 3]
@classmethod
def modify(cls):
cls.collection.append('NICE!')
class B(A):
collection = A.collection[:]
class C(A):
collection = A.collection + [4, 5]
print A.collection
# [1, 2, 3]
print B.collection
# [1, 2, 3]
print C.collection
# [1, 2, 3, 4, 5]
B.modify()
C.modify()
print A.collection
# [1, 2, 3]
print B.collection
# [1, 2, 3, 'NICE!']
print C.collection
# [1, 2, 3, 4, 5, 'NICE!']
One way to think about how python treats classes differently from C++ is what each language does with the class. In C++, each class stands on it's own as a definition of the "layout of the instances member variables", and also adds some metadata to a table that the C++ runtime will use to determine method resolution order.
Python works in a very different way; the class itself doesn't define the layout of attributes; rather when it's time to make an instance of a class, the runtime takes the union of all of the __slots__
defined in each parent class for that particular instance.
In C++, how you define the classes determines how those classes are assembled, but in python, they're just sort of jumbled all together (but still in a well defined way) so that you can't really tell where one class ends and the next begins at the level of the individual instance, and this is really just a consequence of the way that python objects are just "bags of attributes"
精彩评论