Reputation: 21
Suppose the following class hierarchy in Python:
class O:
variable = 0
class A(O):
variable = "abcdef"
class B(O):
variable = 1.0
class X(A, B):
pass
x = X()
When an instance of X gets created, does Python allocate the memory for each variable in the base classes, or only for the resolved variable?
Upvotes: 0
Views: 238
Reputation: 155363
It doesn't allocate any variables when you create an instance of X
; all of your variable
s are class attributes, not instance attributes, so they're attached to their respective classes, not to the instance. X
and instances of X
would see variable
with the value from A
thanks to the order in which it checks base classes for names when the name isn't set on the instance, but all three versions of variable
would exist.
If you did make them instance attributes (assigned to self.variable
in __init__
for each class), and used super()
appropriately to ensure all __init__
s called, there'd only be one copy of self.variable
when you were done initializing (which one survived would depend on whether you initialized self.variable
or called super().__init__()
first in the various __init__
implementations). This is because Python doesn't "resolve" names in the way you're thinking; instance attributes are stored by string name on a dict
under-the-hood, and the last value assigned to that name wins.
The only way to have multiple instance attributes with the "same" name is to make them private, by prefixing them with __
; in that case, with all three defining self.__variable
, there'd be a uniquely name-mangled version of __variable
seen by the methods of each class (and not used by parent or child classes); X
wouldn't see one at all, but methods it inherited from A
would see A
's version, methods inherited from B
would see B
's version, etc.
Upvotes: 1