How to invoke the super constructor in Python?

后端 未结 7 2238
我寻月下人不归
我寻月下人不归 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:39

    Just to add an example with parameters:

    class B(A):
        def __init__(self, x, y, z):
            A.__init__(self, x, y)
    

    Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.

提交回复
热议问题