Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/309.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 从几个类继承相同的函数名_Python_Python 3.x_Class_Inheritance - Fatal编程技术网

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

Python 从几个类继承相同的函数名,python,python-3.x,class,inheritance,Python,Python 3.x,Class,Inheritance,我在读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):

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

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

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

  • 非根类的所有类都必须使用
    super
    传递来自可能定义该方法的任何其他类的方法调用


  • 这里,
    super
    中的
    C.say_hello
    将调用
    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")
    

    你说的“似乎不起作用”是什么意思?您是否收到任何类型的错误消息?错误的输出?要详细说明戴维的评论,你期望得到什么输出?你得到了什么输出?你的问题“我怎样才能从C班同时呼叫A班和B班”并不清楚,但我想你只需要
    A.说你好(self)
    然后
    B.说你好(self)
    super
    将使用MRO中的下一个类。如果你不想枚举实际值,那么你必须给出更多的细节……你对
    super
    的调用调用
    A.say_hello
    ,但该方法不调用
    super
    ,因此调用链结束。在
    C
    的定义中,超类的顺序重要吗?是;如果A在B之前,那么
    A.say_hello
    总是在
    B.say_hello
    之前被调用,这将阻止
    B.say_hello
    被调用。非常有趣的是,我不知道调用的顺序是否重要:因此,如果你像我一样调用class(A,B),它就不起作用,但如果你用B调用,它就起作用了。谢谢你的帮助和帮助explaining@chepner在你的解决方案中,谁是B的父母?在B中使用super().say_hello()时,您将调用哪个父级的方法?
    B
    的父级是
    object
    ,但在
    B.sayhello
    中,您不知道下一个将访问哪个类
    super
    ;这完全取决于
    self
    的运行时类型,其方法解析顺序(MRO)用于确定
    B
    之后的类。
    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")