calling parent constructors in python

This question already has an answer here:

  • How to invoke the super constructor? 5 answers

  • The way you are doing it is indeed the recommended one (for Python 2.x).

    The issue of whether the class is passed explicitly to super is a matter of style rather than functionality. Passing the class to super fits in with Python's philosophy of "explicit is better than implicit".


    Python 3包含一个改进的super(),它允许像这样使用:

    super().__init__(args)
    

    你可以简单地写:

    class A(object):
    
        def __init__(self):
            print "Constructor A was called"
    
    class B(A):
    
        def __init__(self):
            A.__init__(self)
            # A.__init__(self,<parameters>) if you want to call with parameters
            print "Constructor B was called"
    
    class C(B):
    
        def __init__(self):
            # A.__init__(self) # if you want to call most super class...
            B.__init__(self)
            print "Constructor C was called"
    
    链接地址: http://www.djcxy.com/p/26786.html

    上一篇: 多重继承和调用super()

    下一篇: 在Python中调用父构造函数