我正在尝试使用子类中的父方法。下面给出了一个裸骨示例。
class one:
def multiply(self, x, y):
self.x = 500
return self.x*y
class two(one):
def multiplier(self, x, y):
self.x = x
ver1 = one.multiply(one, self.x, y) # here, if I don't pass one as an argument, I get a TypeError
print('The answer of ver1:', ver1)
print('What is self.x btw?', self.x)
ver2 = super().multiply(self.x, y)
print('The answer of ver2:', ver2)
print('What is self.x now?', self.x)
t = two()
t.multiplier(3,4)
打印:
The answer of ver1: 2000
What is self.x btw? 3
The answer of ver2: 2000
What is self.x now? 500
我看了这里,很多答案似乎暗示 ver2
是调用父方法的正确方法,但我不希望 self.x
在子类中改变,所以我的答案是想要的是 ver1
。但是,在 ver1
中,当已经指定 one
是 multiply
的方法时,将 one
作为参数传递似乎是多余的(如果我不传递 { {1}} 作为参数,我得到
one
那么在不改变子类变量的情况下,从父类调用方法的正确方法是什么?
答案 0 :(得分:0)
使用self
,而不是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 很有用:
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)
当已经指定乘法是一个方法时,将一个作为参数传递似乎是多余的(如果我不将一个作为参数传递,我会得到 TypeError: multiply() missing 1 required positional argument: 'y' )
这是因为当你使用 self
时,方法绑定到实例,实例自动作为第一个参数传递。使用one.multiply
时,方法没有绑定,需要手动传递。但这不是正确的方法,正如你的直觉。
我不想在子类中改变self.x
有两个类和一个实例,由于继承,它是两个类的实例。 x 是一个实例属性,因此它属于实例,而不属于两个类中的任何一个。它不能在父类而不是子类或相反的情况下改变。