How to invoke the super constructor in Python?

后端 未结 7 2382
我寻月下人不归
我寻月下人不归 2020-11-22 10:48
class A:
    def __init__(self):
        print(\"world\")

class B(A):
    def __init__(self):
       print(\"hello\")

B()  # output: hello

In all

7条回答
  •  感情败类
    2020-11-22 11:29

    In line with the other answers, there are multiple ways to call super class methods (including the constructor), however in Python-3.x the process has been simplified:

    Python-2.x

    class A(object):
     def __init__(self):
       print "world"
    
    class B(A):
     def __init__(self):
       print "hello"
       super(B, self).__init__()
    

    Python-3.x

    class A(object):
     def __init__(self):
       print("world")
    
    class B(A):
     def __init__(self):
       print("hello")
       super().__init__()
    

    super() is now equivalent to super(, self) as per the docs.

提交回复
热议问题