What is super (ClassName, self) ._ init_ ()

I have a class that looks like this:

#!/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()

I saw some implementation that suggests using super

    def __init__(self, x):
        super(Foo,self).__init__()
        self.x = x
    def bar(self)
        #etc.

My questions:

  • Using super(Foo,self).__init__()
  • How is it different from self.x=x
  • How can I make the top of the code above to get the same result using super()
+4
source share
1 answer

How is it different from self.x=x?

super() Useful only if you are subclassing:

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

better than setting self.x = xin Bar __init__.

The difference is that you Bardon’t have to worry about implementation Foo.

Foo , self.x = 2 * x, Bar ( - , ).

super(), .

+3

Source: https://habr.com/ru/post/1534198/


All Articles