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

时间:2017-12-13 20:07:55

标签: python python-3.x class inheritance

我正在阅读stackoverflow上的this线程,但根据用户看起来解决方案是错误的,最重要的是,它无法解决我的问题,我不知道是否因为答案是在python 2或whatnow。

但是,让我说我有这个代码

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()这样的事情,但这似乎不起作用,我不知道为什么。

1 个答案:

答案 0 :(得分:4)

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

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

  2. 所有不是root的类必须使用super来传递从可能定义该方法的任何其他类调用该方法。

  3. # 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()
    

    此处super中的C.say_hello会致电B.say_hellosuper将致电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")
    
相关问题