[英]Base class method not being overridden as expected
I have the following code:我有以下代码:
class A():
def __init__(self,param1 = None):
self.param1 = param1
def method1(self):
print("hello")
def method2(self):
self.method1()
class B(A):
def __init__(self, param1):
super().__init__(param1)
def method1(self):
print("goodbye")
b = B()
b.method2()
The output for this code is "hello" despite method1
being overwritten.尽管
method1
被覆盖,但此代码的 output 是“hello”。 I would expect (and this is the intented behaviour) to get "goodbye" as output, and I dont know why is this working like this.我希望(这是有意的行为)作为 output 得到“再见”,我不知道为什么会这样。
Is there any way to force Python to execute the overwritten methods whenever they exist?有没有办法强制 Python 在覆盖的方法存在时执行它们?
You didn't pass A into B when calling the class B into b.将 class B 调用到 b 时,您没有将 A 传递到 B。 The right output is given when you do so.
这样做时会给出正确的 output。
b = B(A)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.