Inheritance
You need a specialized version of an existing class.
Use inheritance to create a subclass of an existing class and add new member variables and methods.
By default, all new classes that you create are subclasses of object. You can change this by specifying the class you want to use as a superclass in parentheses after the class name in a class definition. The following example defines a class (Employee) as a subclass (Person) and adds a new member variable (salary) and an extra method (give_raise):
class Employee(Person): def __init__(self, first_name, surname, tel, salary): super().__init__(first_name, surname, tel) self.salary = salary def give_raise(self, amount): self.salary = self.salary + amount |
Note that the preceding example is for Python 3. For Python 2, you can’t use super the same way. Instead, you must write:
class Employee(Person): def __init__(self, first_name, surname, tel, salary): Person.__init__(self, first_name, surname, tel) self.salary = salary def give_raise(self, amount): self.salary = self.salary + amount |
Discussion
In both these examples, the initializer method for the subclass first uses the initializer method of the parent class (superclass) and then adds the member variable. This has the advantage that you do not need to repeat the initialization code in the new subclass.
See Also
See Recipe 5.24 for information on defining a class.
The Python inheritance mechanism is actually very powerful and supports multiple inheritance—where a subclass inherits from more than one superclass. For more on inheritance, see the official documentation for Python.