Difference between Father .__ init (self) and super (Father, self) .__ init __ ()

3

I'm a bit doubtful about the inheritance issue in python .

In the following test, I expected that quack would print the same value for the two classes I created:

class A(object):
    a,b = (None, None)
    def __init__(self):
        self.a = 'a'

    def quack(self):
        return 'retorno "%s" ' % self.a

class B(A):

    def __init__(self):
        super(A, self).__init__()
        self.b = 'b'

My test was done like this:

b = B()
a = A()

print(b.quack())
print(a.quack())

The output was:

retorno "None" 
retorno "a"

But I thought the two of them should return the same thing.

The inheritance of the a property only worked as I expected when I changed the super snippet to this:

A.__init(self)

Return:

retorno "a"
retorno "a"

Having these two cases, what is the difference between the two statements I created?

Why did not super use the parent class method?

    
asked by anonymous 12.12.2015 / 23:40

1 answer

3

The problem is that super should not be called in the parent class, but in the class itself:

class B(A):
    def __init__(self):
        super(B, self).__init__()
        self.b = 'b'

Since the idea of super is not to call the method in a specific class (for that the second form you used is the right one), but to call the method using the same python inheritance rules, just ignoring the current class:

class A(object): ...
class B(A): ...
class C(A): ...
class D(B, C): ...
class E(B): ...

class F(D, E):
    def __init__(self):
        super(F, self).__init__()

This example above will attempt to find a method __init__ in all classes of the hierarchy, except and the F itself. And the order he is going to get is defined by the inheritance process (which I regretfully do not know ...). That would be worth some other method too, type super(F, self).foo() .

class F(D, E):
    def __init__(self):
        super(E, self).__init__()

If you used this code, on the other hand, Python would only fetch a __init__ in the superclasses of E , that is, B and then A . Even though C has a __init__ , and C is one of the F superclasses, it would not be fetched in that case. And in particular, the E itself is not fetched (since super assumes it is to ignore E , just as it ignored F in the previous example).

    
12.12.2015 / 23:54