The inheritance of attributes using __init__

user1111042 picture user1111042 · Jan 13, 2012 · Viewed 39.4k times · Source

I'm Java person who just started learning Python. Take this example:

class Person():
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone

class Teenager(Person):
    def __init__(self, name, phone, website):
        self.name=name
        self.phone=phone
        self.website=website

I'm sure there's a lot of redundant code (I know in Java, there are a lot of redundancies for the bit of code above).

Which parts are redundant with respect to which attributes are already inherited from the parent class?

Answer

murgatroid99 picture murgatroid99 · Jan 13, 2012

When writing the __init__ function for a class in python, you should always call the __init__ function of its superclass. We can use this to pass the relevant attributes directly to the superclass, so your code would look like this:

class Person(object):
    def __init__(self, name, phone):
        self.name = name
        self.phone = phone
class Teenager(Person):
    def __init__(self, name, phone, website):
        Person.__init__(self, name, phone)
        self.website=website

As others have pointed out, you could replace the line

Person.__init__(self, name, phone)

with

super(Teenager, self).__init__(name, phone)

and the code will do the same thing. This is because in python instance.method(args) is just shorthand for Class.method(instance, args). If you want use super you need to make sure that you specify object as the base class for Person as I have done in my code.

The python documentation has more information about how to use the super keyword. The important thing in this case is that it tells python to look for the method __init__ in a superclass of self that is not Teenager