Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/291.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 带super()的第二个基类的访问方法_Python_Class_Oop_Python 3.x_Inheritance - Fatal编程技术网

Python 带super()的第二个基类的访问方法

Python 带super()的第二个基类的访问方法,python,class,oop,python-3.x,inheritance,Python,Class,Oop,Python 3.x,Inheritance,请给我解释一下。如果我执行此命令: class Base1: def foo(self): print('in Base1.foo') b1 = Base1() b1.foo() class Base2: def foo(self): print('in Base2.foo') b2 = Base2() b2.foo() class Child1(Base1, Base2): def foo(self): supe

请给我解释一下。如果我执行此命令:

class Base1:
    def foo(self):
        print('in Base1.foo')

b1 = Base1()
b1.foo()


class Base2:
    def foo(self):
        print('in Base2.foo')

b2 = Base2()
b2.foo()

class Child1(Base1, Base2):
    def foo(self):
        super(Child1,self).foo()

c1 =  Child1()
c1.foo()

class Child2(Base1, Base2):
    def foo(self):
        super(Base1,self).foo()

c2 =  Child2()
c2.foo()
我明白了:

in Base1.foo
in Base2.foo
in Base1.foo
in Base2.foo
我理解输出的前三行。但是为什么我必须将第一个基类的名称指定给
super()
,才能获得第二个基类的方法呢?

您正在使用,或MRO。Python类继承层次结构是线性化的,根据一个名为的系统,给定了特定的顺序

super()
使用该顺序查找该顺序中的下一个属性(包括方法)。给定一个当前实例和一个类,它将搜索给定类中过去的属性的顺序。对于两个
Child*
类,MRO首先列出
Child*
类,然后是
Base1
Base2
。在上一个示例中,您告诉
super()
Base1
之后的下一个类开始查找该MRO,因此只剩下
Base2.foo()

您可以通过拨打以下电话向任何班级询问其MRO:

你在和MRO捣乱。Python类继承层次结构是线性化的,根据一个名为的系统,给定了特定的顺序

super()
使用该顺序查找该顺序中的下一个属性(包括方法)。给定一个当前实例和一个类,它将搜索给定类中过去的属性的顺序。对于两个
Child*
类,MRO首先列出
Child*
类,然后是
Base1
Base2
。在上一个示例中,您告诉
super()
Base1
之后的下一个类开始查找该MRO,因此只剩下
Base2.foo()

您可以通过拨打以下电话向任何班级询问其MRO:


我知道方法的解析顺序,但我不知道super()会得到行中的“next”基类。。。thanksI知道方法的解析顺序,但我不知道super()会得到行中的“下一个”基类。。。谢谢
>>> Child2.mro()
[<class '__main__.Child2'>, <class '__main__.Base1'>, <class '__main__.Base2'>, <class 'object'>]
>>> super(Child2, Child2()).foo
<bound method Base1.foo of <__main__.Child2 object at 0x10f40ff98>>
>>> super(Base1, Child2()).foo
<bound method Base2.foo of <__main__.Child2 object at 0x10f40ffd0>>
>>> super(Base2, Child2()).foo
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'super' object has no attribute 'foo'