Reputation: 21923
I have a class A
made by someone else, that I cannot edit:
class A:
def __init__(self, x):
self.x = x
Now I'm trying to inherit my own class B
from A
, and have x
as a property instead of an attribute.
Is this possible?
I already tried:
class B(A):
def __init__(self, x):
super().__init__(x)
@property
def x(self):
return super().x
@x.setter
def x(self, x):
super().x = x
print(x) # my stuff goes here
But as I expected, it's not possible: AttributeError: 'super' object has no attribute 'x'
Is there any other method, some workaroud maybe?
Upvotes: 0
Views: 1051
Reputation: 1122012
No, you cannot use super()
for anything other than class attributes; x
is an instance attribute, and there is no inheritance mechanism for attributes.
Instance attributes live in a single namespace; there is no 'parent instance' attribute namespace.
You can still reach the attribute in the instance __dict__
object:
class B(A):
@property
def x(self):
return self.__dict__['x']
@x.setter
def x(self, x):
self.__dict__['x'] = x
print(x) # my stuff goes here
A property is a data descriptor, meaning that it is looked up before the instance attributes are consulted (see the descriptor howto), but you can still access it directly.
Upvotes: 2