简体   繁体   English

超级构造函数中的打印语句不打印

[英]print statements in super constructor don't print

class A():
    def __init__(self):
        print("A")

class B():
    def __init__(self):
        super()
        print("B")

B()

This code prints "B" . 此代码显示"B" My expectation was that it would print 我的期望是它将打印

A
B

or at least 或至少

B
A

. Why does it only print B? 为什么只打印B?

  1. class B does not inherit of class A B类不继承A类
  2. This is not the good syntax, super does not call constructor, it returns reference to parent class (and must be passed the type of current class and a reference to it (self)) 这不是一个好的语法,super不会调用构造函数,它返回对父类的引用(并且必须传递当前类的类型和对其的引用(自身))

Correction: 更正:

class A(object):
  def __init__(self):
    print "A"

class B(A): # Inherit A class
  def __init__(self):
    super(B, self).__init__()  # Call A constructor
    print "B"

super by itself just returns a reference to the parent class. super本身仅返回对父类的引用。 You actually need to call the relevant method: 您实际上需要调用相关方法:

 super().__init__()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM