Well consider the following minimal example:
class base:
def __init__(self, mass):
self.mass = mass
def price()
return self.mass * 10
class deriv(base):
def __init__(self, payload, *args, **kwargs):
super().__init__(mass=0, *args, **kwargs)
#mass of super is shadowed anyways, so setting it to 0
self.payload = payload
@property
def mass(self):
return self.payload #would be a more complex calculation
#NO setter, since it's illogical due to it being complex
t = deriv(1000)
Basically the derived class "uniqueness" is that the mass is no longer a simple value that can be set & changed. But instead it is based on a complex function based on several other, new, properties.
Now above code "looks" good to me: mass
is shadowed in the derived class by the property. In the base class initializer the derived class does not yet fully exist, so writing there should write into the base class properties (a shadowed object). Yet for the price
function it should look into the derived class' property.
So I tried to execute this:
line 3, in __init__
self.mass = mass
AttributeError: can't set attribute
Ok it looks as if during __init__
of the baseclass python is already aware of the properties from the derived class. That is "strange", especially in the light of another (silly) derived class, which does work:
class deriv2(base):
def __init__(self, mass, *args, **kwargs):
super().__init__(mass=0, *args, **kwargs)
self.mass = mass*2
So how would I make this work? I rather change as little to both the interface of the object (still want to have a mass property in for deriv
) as well as as little for base
(deriv
is the "weird" one, so that one is responsible for making sure he works).