Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/15.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 3中的super()怪诞_Python_Python 3.x_Super - Fatal编程技术网

Python 3中的super()怪诞

Python 3中的super()怪诞,python,python-3.x,super,Python,Python 3.x,Super,我知道这之前已经讨论过很多次了,但是从来没有人解释过“引擎盖下”发生了什么 有人能详细解释为什么最后一行代码中的注释会导致出现错误吗?我知道那个对象。uuu init_uuuuu不接受任何参数,但是当行被注释掉时,为什么代码可以工作呢 class A: def __init__(self, a): print("A constructor") super().__init__(a) self.a = a print("A constructo

我知道这之前已经讨论过很多次了,但是从来没有人解释过“引擎盖下”发生了什么

有人能详细解释为什么最后一行代码中的注释会导致出现错误吗?我知道那个对象。uuu init_uuuuu不接受任何参数,但是当行被注释掉时,为什么代码可以工作呢

class A:
   def __init__(self, a):
      print("A constructor")
      super().__init__(a)
      self.a = a
      print("A constructor end")

class B:
   def __init__(self, b):
      print("B constructor")
      super().__init__()
      self.b = b
      print("B constructor end")


class C(A, B):
   def __init__(self, x):
      super().__init__(x)


c = C(42)
#a = A(33)

在Python3中,每个方法都成为一个闭包,为定义的“当前类”添加了一个隐藏值。这可以通过
super()
(不带参数)访问

Super返回一个使用类的方法解析顺序(MRO)的对象,对于C实例,在A之后有B

如果不在MRO中找到B,则在will call对象中的
super()。\uuuuu init\uuuuu
。\uuuuu init\uuuuuuu,您无法向其传递任何参数

您可以通过查看SomeClass来查看某个类的MRO

虽然主要讨论的是2.x,但您可能想阅读