简体   繁体   中英

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" . My expectation was that it would print

A
B

or at least

B
A

. Why does it only print B?

  1. class B does not inherit of class 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))

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. You actually need to call the relevant method:

 super().__init__()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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