Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/305.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
Python2.7方法解析顺序_Python_Python 2.7_Multiple Inheritance_Method Resolution Order - Fatal编程技术网

Python2.7方法解析顺序

Python2.7方法解析顺序,python,python-2.7,multiple-inheritance,method-resolution-order,Python,Python 2.7,Multiple Inheritance,Method Resolution Order,我在Python中使用多重继承时遇到了一些问题,无法理解我做错了什么 我有三个类A,B,C定义如下,它不工作 class A(object): def __init__(**kwargs): . . class B(object): def __init__(**kwargs): # prepare a dictionary "options" with the options used to call A super(B,self).__ini

我在Python中使用多重继承时遇到了一些问题,无法理解我做错了什么

我有三个类A,B,C定义如下,它不工作

class A(object):
   def __init__(**kwargs):
     .
     .

class B(object):
   def __init__(**kwargs):
    # prepare a dictionary "options" with the options used to call A
    super(B,self).__init__(**options)

   def coolmethod(x):
      #some cool stuff
对于A和B,我没有任何问题

我想创建一个从a和B继承的第三类C 因此,我可以使用B中定义的coolmethod,但希望使用A中定义的构造函数

试图定义
类别C(A,B)
不起作用,因为没有定义MRO

但是定义
类C(B,A)
不允许我使用A.init而不是B.init

如何解决此问题?

您可以直接调用A.\uuu init\uuuu()而不是在C中使用super():

您可以直接调用.\uuuu init\uuuuu()而不是在C中使用super():

你可以用

class A(object):
    def __init__(self, **kwargs):
        super(A, self).__init__(**kwargs)
如果您希望从一个或其他对象获得多重继承。这样,
A.。\uuuu init\uuuu
将始终被调用

顺序很重要,因为方法解析在python中的工作方式。如果您让C从(A,B)继承,这意味着如果您在C上调用同时存在于A和B上的方法,则会选择A上的方法(它具有优先权)。如果您在类A中编写
super(A,self).method
,则表示您希望扩展
method
提供的功能。因此,如果A和B都有这样的扩展,而C继承自这两个扩展,那么跳过一个这样的扩展是很奇怪的。这就是为什么当您调用
C.method
时,它将执行
A.method
,当调用
super(A,self.method
时,它将调用
B.method
。换句话说,就好像A是为了方法扩展而从B继承的。当C从(B,A)继承时,这是不同的

请注意,
\uuuu init\uuuu
的第一个参数应该始终是
self
,就像对每个方法一样。

您可以使用

class A(object):
    def __init__(self, **kwargs):
        super(A, self).__init__(**kwargs)
如果您希望从一个或其他对象获得多重继承。这样,
A.。\uuuu init\uuuu
将始终被调用

顺序很重要,因为方法解析在python中的工作方式。如果您让C从(A,B)继承,这意味着如果您在C上调用同时存在于A和B上的方法,则会选择A上的方法(它具有优先权)。如果您在类A中编写
super(A,self).method
,则表示您希望扩展
method
提供的功能。因此,如果A和B都有这样的扩展,而C继承自这两个扩展,那么跳过一个这样的扩展是很奇怪的。这就是为什么当您调用
C.method
时,它将执行
A.method
,当调用
super(A,self.method
时,它将调用
B.method
。换句话说,就好像A是为了方法扩展而从B继承的。当C从(B,A)继承时,这是不同的


请注意,
\uuuu init\uuu
的第一个参数应该始终是
self
,就像每个方法一样。

谢谢。。这很容易。。我不明白为什么类声明中的顺序很重要…请参阅下面我的答案,了解有关顺序的解释。谢谢。。这很容易。。我不明白为什么类声明中的顺序很重要……关于顺序的解释,请参阅下面的答案。