Abdelouahab
Abdelouahab

Reputation: 7559

When to use Parent.__init__(self) and not to use it?

I have this code:

class Pere():
    def __init__(self, nom):
        self.nom = nom
    def yeux(self):
        print 'les yeux bleus'

class Mere():
    def __init__(self, nom):
        self.nom = nom
    def taille(self):
       print 'je suis longue!'

class Enfant(Pere, Mere):
    pass

And in some tutorials speaking about inheritance, they use ParentClass.__init__(self, *args) for the child constructor.

Here is the example where it is used:

class Person(object):
    def __init__(self, nom, age):
        self.name = nom
        self.age = age
    def __str__(self):
        return 'je suis {0}, et j\'ai {1} ans'.format(self.name, self.age)

class Militaire(Person):
    def __init__(self, nom, age, grade):
        Person.__init__(self, nom, age)
        self.grade = grade
    def __str__(self):
        return Person.__str__(self) + ' et je suis un {0}'.format(self.grade)

When to use it?

In multiple inheritance, we dont need it (write it twice for example if it exists)?

Upvotes: 0

Views: 122

Answers (1)

Alex Martelli
Alex Martelli

Reputation: 882691

The unbound-method call (Parent.__init__(self, ...)) does not work well in general with multiple inheritance -- just like simply inheriting __init__ (if delegating to the parent is all you do in the method in your subclass, don't -- just omit defining the method in the subclass so it inherits from the superclass).

In your example that's totally moot since both superclasses have identical implementations of __init__ (in the original Q, now edited to change that), so it doesn't really matter what you do.

More generally, that's what super was introduced for -- it works smoothly in Python 3, a bit less in Python 2 (in the latter case, only for new-style classes, normally inheriting from object -- but then nobody should be defining old-style classes any more!-), but it still works for multiple inheritance much better than older approaches such as explicitly calling Parent.__init__ (it only works well if every class in the hierarchy cooperates, though).

See e.g Understanding Python super() with __init__() methods for more about super and the like.

Upvotes: 3

Related Questions