super(ClassName,self)有什么用._ init_()

nev*_*int 5 python oop class

我有一个看起来像这样的课程:

#!/usr/bin/env python
class Foo:
    def __init__(self, x):
        self.x = x
    def bar(self):
        self.bar1_out = self.x + 5
        self.bar2_out = self.x + 1
        return (self.bar1_out,self.bar2_out)
    def qux(self,myvalue = None):
        first, second = myvalue or self.bar()
        return first + 3, second + 6

def main():
    """docstring for main"""
    f = Foo(5)

    mbr_out1, mbr_out2 = f.bar()
    print mbr_out1, "\t", mbr_out2

    mqx_out1, mqx_out2 = f.qux()
    print mqx_out1, "\t", mqx_out2

    qout1, qout2 = f.qux((1))
    print qout1, "\t", qout2

if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

我看到了一些建议使用的实现 super

    def __init__(self, x):
        super(Foo,self).__init__()
        self.x = x
    def bar(self)
        #etc.
Run Code Online (Sandbox Code Playgroud)

我的问题是:

  1. 有什么用? super(Foo,self).__init__()
  2. 它与...有何不同? self.x=x
  3. 如何通过使用使我的代码在上面产生相同的结果 super()

glg*_*lgl 5

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
Run Code Online (Sandbox Code Playgroud)

比制定出更好self.x = xBar__init__

所不同的是,Bar无需关心的实现Foo

如果您选择以Fooset的方式进行更改self.x = 2 * x,那么您也不必进行更改Bar(它甚至可能位于差异文件中-几乎可以保证看不到该更改)。

在您的示例中,super()没有子类是没有意义的。