gpt4 book ai didi

Python调用父方法多重继承

转载 作者:太空狗 更新时间:2023-10-29 17:44:06 26 4
gpt4 key购买 nike

所以,我有这样的情况。

class A(object):
def foo(self, call_from):
print "foo from A, call from %s" % call_from


class B(object):
def foo(self, call_from):
print "foo from B, call from %s" % call_from


class C(object):
def foo(self, call_from):
print "foo from C, call from %s" % call_from


class D(A, B, C):
def foo(self):
print "foo from D"
super(D, self).foo("D")

d = D()
d.foo()

代码的结果是

foo from D
foo from A, call from D

我想从 D 类中调用所有父方法,在本例中为 foo 方法,而不是像 A 这样在父类中使用 super。我只想从 D 类中调用 super。 ABC 类就像混合类,我想从 D 调用所有 foo 方法>。我怎样才能做到这一点?

最佳答案

你可以像这样使用__bases__

class D(A, B, C):
def foo(self):
print("foo from D")
for cls in D.__bases__:
cls().foo("D")

有了这个改变,输出将是

foo from D
foo from A, call from D
foo from B, call from D
foo from C, call from D

关于Python调用父方法多重继承,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20450911/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com