在Python中调用构造函数的顺序

liv*_*hak 4 python

#!/usr/bin/python

class Parent(object):        # define parent class
   parentAttr = 100
   def __init__(self):
      print "Calling parent constructor"

   def parentMethod(self):
      print 'Calling parent method'

   def setAttr(self, attr):
      Parent.parentAttr = attr

   def getAttr(self):
      print "Parent attribute :", Parent.parentAttr


class Child(Parent): # define child class
   def __init__(self):
      print "Calling child constructor"

   def childMethod(self):
      print 'Calling child method'


c = Child()          # instance of child
Run Code Online (Sandbox Code Playgroud)

我调用了这里创建了一个Child类的实例.它似乎没有调用父类的构造函数.输出如下所示.

Calling child constructor
Run Code Online (Sandbox Code Playgroud)

例如,在C++中调用派生类的构造函数时,首先调用基类构造函数.为什么在Python中不会发生这种情况?

Jim*_*son 9

来自Python禅宗:

显式优于隐式.

Python应该在子构造函数之前或之后调用父构造函数吗?有什么论据?不知道,它让你决定.

class Child(Parent): # define child class
    def __init__(self):
        super(Child, self).__init__()  # call the appropriate superclass constructor
        print "Calling child constructor"
Run Code Online (Sandbox Code Playgroud)

有关使用的好处,另请参阅此StackOverflow帖子super().


小智 5

您需要明确地__init__在子类的方法中调用父构造函数.尝试:

class Child(Parent): # define child class
   def __init__(self):
      Parent.__init__(self)
      print "Calling child constructor"
Run Code Online (Sandbox Code Playgroud)