How to invoke the super constructor in Python?

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

    One way is to call A's constructor and pass self as an argument, like so:

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

    The advantage of this style is that it's very clear. It call A's initialiser. The downside is that it doesn't handle diamond-shaped inheritance very well, since you may end up calling the shared base class's initialiser twice.

    Another way is to use super(), as others have shown. For single-inheritance, it does basically the same thing as letting you call the parent's initialiser.

    However, super() is quite a bit more complicated under-the-hood and can sometimes be counter-intuitive in multiple inheritance situations. On the plus side, super() can be used to handle diamond-shaped inheritance. If you want to know the nitty-gritty of what super() does, the best explanation I've found for how super() works is here (though I'm not necessarily endorsing that article's opinions).

    0 讨论(0)
提交回复
热议问题