super(ClassName,self)的用法是什么?

这个问题在这里已经有了答案:

  • 用__init __()方法理解Python super()7个答案

  • 它与self.x=x什么不同?

    super()只在你继承子类时才有用:

    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
    

    比在Bar__init__设置self.x = x要好。

    区别在于Bar不需要关心Foo的实现。

    如果您选择以设置self.x = 2 * x的方式更改Foo ,那么您将不必更改Bar (甚至可能位于差异文件中 - 看不到这一点几乎得到保证)。

    在你的例子中,没有必要使用super()因为你没有子类。

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

    上一篇: What is the use of super(ClassName,self).

    下一篇: [python]: confused by super()