[英]In Python, is there any way to call a child class's method override from its parent class?
[英]The proper way to call a parent method from a child class
我正在尝试使用子 class 的父方法。 下面给出了一个简单的例子。
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
在子 class 中发生变化,所以我想要的答案是ver1
。 但是,在ver1
中,当已经指定multiply
是one
的方法时,将one
作为参数传递似乎是多余的(如果我不将one
作为参数传递,我会得到
TypeError: multiply() missing 1 required positional argument: 'y'
那么从父 class 调用方法而不更改子 class 中的变量的正确方法是什么?
使用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
时,方法不绑定,需要手动传递。 但这不是您直觉的 go 的正确方法。
我不希望 self.x 在子 class 中发生变化
由于 inheritance,有两个类和一个实例,这是两个类的实例。 x 是一个实例属性,因此它属于实例,而不属于两个类中的任何一个。 它不能在父母而不是孩子 class 或相反的情况下改变。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.