The inheritance of attributes using __init__
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
Slightly cleaner way I like to do this:
class Teenager(Person):
def __init__(self, *args, **kwargs):
self.website=kwargs.pop('website')
super(Teenager, self).__init__(*args, **kwargs)
It doesn't make much of a difference in this case, but when you have an __init__
with a ton of arguments, it makes life easier.
All of the examples so far have been for Python 2.x but here's a solution for Python 3.x that makes use of a shorter version of super() and doesn't inherit from object.
class Person:
def __init__(self, name, phone):
self.name = name
self.phone = phone
class Teenager(Person):
def __init__(self, name, phone, website):
super().__init__(name, phone)
self.website = website