从几个类继承相同的函数名

Pla*_*il1 2 python inheritance class python-3.x

我正在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()
Run Code Online (Sandbox Code Playgroud)

如何在不更改函数名称的情况下从 C 类调用 A 类和 B 类?正如我在另一个线程中读到的那样,您可以执行类似的操作,super(B, self).say_hello()但这似乎不起作用,但我不知道为什么。

che*_*ner 5

super正确使用,需要正确设计所涉及的每个类。除其他事项外:

  1. 一个类应该是该方法的“根”,这意味着它不会用于super进一步委托调用。此类必须出现在提供该方法的任何其他类之后。

  2. 所有不是根的类都必须用于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()
Run Code Online (Sandbox Code Playgroud)

在这里,superinC.say_hello将调用B.say_hello,谁将super调用A.say_hello


如果您不想遵循 using 的要求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")
Run Code Online (Sandbox Code Playgroud)

  • 是的; 如果 A 在 B 之前,那么 `A.say_hello` 将始终在 `B.say_hello` 之前被调用,这将根本阻止 `B.say_hello` 被调用。 (2认同)