What is the use of super(ClassName,self).

This question already has an answer here:

  • Understanding Python super() with __init__() methods [duplicate] 7 answers

  • How does it differ from self.x=x ?

    super() is only useful if you subclass:

    class Foo(object):
        def __init__(self, x):
            self.x = x
    
    class Bar(Foo):
        def __init__(self, x):
            super(Bar, self).__init__(x)
            self.initial_status = False
    

    is better than setting self.x = x in Bar 's __init__ .

    The difference is that Bar doesn't need to care about the implementation of Foo .

    If you choose to change Foo in a way which sets self.x = 2 * x , then you won't have to change Bar as well (which might even sit in a difference file - failure to see this is almost guaranteed).

    In your example, there is no point to use super() as you don't subclass.

    链接地址: http://www.djcxy.com/p/30036.html

    上一篇: Python的基本继承

    下一篇: super(ClassName,self)的用法是什么?