[英]Python: Overriding method in child class skipping one of the Base Class
I have two base classes A
and B
each of them have a method myfunc
, which prints out a different character.我有两个基类
A
和B
每个基类都有一个方法myfunc
,它打印出不同的字符。
class A:
def myfunc(self):
print('A')
class B:
def myfunc(self):
print('B')
I have one more class C
which is inheriting from A
and B
both.我还有一个
class C
,它继承自A
和B
In class C
I have overridden myfunc
and called super
over it.在
class C
我覆盖了myfunc
并对其调用了super
。
class C(B, A):
def myfunc(self):
super().myfunc()
Now if I execute following code, it prints only one character现在,如果我执行以下代码,它只会打印一个字符
x = C()
x.myfunc()
Output:输出:
B
I tried print(C.__mro__)
which gives me (<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
So it should go to class A
and print character A
also.我试过
print(C.__mro__)
这给了我(<class '__main__.C'>, <class '__main__.B'>, <class '__main__.A'>, <class 'object'>)
所以它应该去到class A
并打印字符A
right?对?
Also if I switch the order of inheritance like C(A,B)
it and use the same code , it is skipping class B
.此外,如果我像
C(A,B)
那样切换继承顺序并使用相同的代码,它会跳过class B
。
My questions:我的问题:
class A
?class A
?myfunc
method in both classes A
and B
A
类和B
类中执行myfunc
方法I looked up similar discussion but found it confusing.我查找了类似的讨论,但发现它令人困惑。
Answering question 1:回答问题1:
It is skipping myFunc
on class A because what python does when you call super.myFunc()
is search for the first function with name myFunc
in all the base classes (in this case B
and A
) and it does that in order, so it first look for myFunc
in class B
.它跳过类 A 上的
myFunc
因为当您调用super.myFunc()
时,python 所做的是在所有基类(在本例中为B
和A
)中搜索名称为myFunc
的第一个函数,并按顺序执行此操作,因此它首先在B
类中查找myFunc
。 So, because there is a function named myFunc
in class B
python stop searching and executes only that.因此,因为
B
类中有一个名为myFunc
的函数,所以 python 停止搜索并仅执行该函数。
Answering question 2:回答问题2:
There is a trivial way of doing that which is this:有一种简单的方法可以做到这一点:
class A:
def f(self):
print('A')
class B:
def f(self):
print('B')
class C(B, A):
def f(self):
A.f(self)
B.f(self)
c = C()
c.f()
Basically you can call any function of any class and then pass the instance as the first argument ( self
).基本上你可以调用任何类的任何函数,然后将实例作为第一个参数(
self
)传递。 I believe you can't execute both functions with only one call, you will need to make a call for each one.我相信你不能只用一个调用来执行这两个函数,你需要为每个函数调用一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.