Use self
, not one
:
class two(one):
def multiplier(self, x, y):
self.x = x
ver1 = self.multiply(x, y)
print('The answer of ver1:', ver1)
print('What is self.x btw?', self.x)
Super is useful if you override the same method but want access to the parent:
class two(one):
def multiply(self, x, y):
self.x = x
ver2 = super().multiply(x, y)
print('The answer of ver2:', ver2)
print('What is self.x now?', self.x)
It seems redundant to pass one as an argument when it is already specified that multiply is one's method (if I don't pass one as an argument, I get TypeError: multiply() missing 1 required positional argument: 'y')
This is because when you use self
, the method is bound to the instance and the instance is passed automatically as first parameter. When using one.multiply
, the method is not bound and you need to pass it manually. But this is not the right way to go, as you intuited.
I don't want self.x to change in the child class
There are two classes and an instance which is an instance of both classes due to inheritance. x is an instance attribute, so it belongs to the instance, not to any of both classes. It can't change in parent and not child class or the opposite.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…