Question 7.6: Inheritance You need a specialized version of an existing cl......

Inheritance

You need a specialized version of an existing class.

Step-by-Step
The 'Blue Check Mark' means that this solution was answered by an expert.
Learn more on how do we answer questions.

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.

Related Answered Questions

Question: 7.14

Verified Answer:

Import sys and use its argv property, as shown in ...
Question: 7.15

Verified Answer:

Python has a library for the Simple Mail Transfer ...
Question: 7.13

Verified Answer:

Python has an extensive library for making HTTP re...
Question: 7.12

Verified Answer:

Use the random library: >>> import ran...
Question: 7.16

Verified Answer:

Use the bottle Python library to run a pure Python...
Question: 7.11

Verified Answer:

Use the import command: import random Discus...
Question: 7.8

Verified Answer:

To read a file’s contents, you need to use the fil...
Question: 7.7

Verified Answer:

Use the open, write, and close functions to open a...