我在stackoverflow上阅读了此线程,但根据用户的说法,解决方案似乎是错误的,最重要的是,它无法解决我的问题,我不知道它是否因为答案是在python 2中或什么。
但是,可以说我有这个代码
class A:
def say_hello(self):
print("Hi")
class B:
def say_hello(self):
print("Hello")
class C(A, B):
def say_hello(self):
super().say_hello()
print("Hey")
welcome = C()
welcome.say_hello()
如何在不更改函数名称的情况下从C类中调用A类和B类?正如我在另一个线程中所读到的那样,您可以做类似super(B, self).say_hello()
的事情,但这似乎不起作用,但是我不知道为什么。
要正确使用 super
,类都需要正确设计。除其他事项:
-
一个类应该是该方法的"根",这意味着它不会使用
super
进一步委派呼叫。此类必须在提供该方法的任何其他类后出现。 -
所有不是根类的类都必须使用
super
从任何可能定义方法的其他类中传递该方法。
# Designated root class for say_hello
class A:
def say_hello(self):
print("Hi")
# Does not inherit say_hello, but must be aware that it is not the root
# class, and it should delegate a call further up the MRO
class B:
def say_hello(self):
super().say_hello()
print("Hello")
# Make sure A is the last class in the MRO to ensure all say_hello
# methods are called.
class C(B, A):
def say_hello(self):
super().say_hello()
print("Hey")
welcome = C()
welcome.say_hello()
在这里,C.say_hello
中的super
将调用B.say_hello
,其super
将致电A.say_hello
。
如果您不希望使用super
的要求,请明确调用对方的方法。使用super
。
class A:
def say_hello(self):
print("Hi")
class B:
def say_hello(self):
print("Hello")
class C(A, B):
def say_hello(self):
A.say_hello(self)
B.say_hello(self)
print("Hey")
如果您不想决定哪个类(A或B)是指定的根类,则还可以为A和B。
实现抽象超类from abc import ABC, abstractmethod
class ISayHello(ABC):
@abstractmethod
def say_hello(self):
pass
class A(ISayHello):
def say_hello(self):
super().say_hello()
print("Hi")
class B(ISayHello):
def say_hello(self):
super().say_hello()
print("Hello")
class C(B,A):
def say_hello(self):
super().say_hello()
print("Hey")
welcome_c = C()
welcome_c.say_hello()
,如果您还有与c。
class D(A,B):
def say_hello(self):
super().say_hello()
print("Hey")
welcome_d = D()
welcome_d.say_hello()