Python Introduction | Using Classes | Class Inheritance
One of the main advantages of defining a class is reuse. Once a class has been created, it can be used in many places.
As a program grows, you may want to improve an existing class. Directly modifying a widely used class can be difficult. Inheritance provides a convenient alternative.
Inheritance creates a new class from an existing class. The new class receives the features of the original class.
Define an inherited class as follows.
class ClassName(BaseClass):
... class contents ...
The original class is called the base class, and the newly created class is called the derived class.
class Member:
name = ""
def __init__(self,str):
self.name = str
def showMsg(self):
print("Hello," + self.name + ".How are you?")
class PowerMember (Member):
mail = ""
def __init__(self,str1,str2):
self.name = str1
self.mail = str2
def showMsg(self):
print("Hello," + self.name + ".")
print("Your mail address is '" + self.mail + "'.")
taro = Member("Taro")
taro.showMsg()
hanako = PowerMember("Hanako","hanako@flower.com")
hanako.showMsg()
This example creates a derived class named PowerMember by inheriting from Member.
PowerMember defines __init__(self, str1, str2) with two arguments and assigns values to self.name and self.mail.
Although PowerMember defines only mail, it can also store self.name because the base class Member provides name. A derived class inherits the features of its base class.
Inheritance applies to methods as well as member variables. It lets you extend existing classes with additional functionality.
Python libraries include many classes that can be reused through inheritance. Types such as lists, tuples, and ranges also share sequence-related behavior.