Python class inheritance and polymorphism
In OOP (Object oriented programming) programming, when we define a class, we can inherit from an existing class, a new class called a subclass (subclass), The inherited class is called the base class, the parent class, or the superclass (base class, Super Class).
Let's start by defining a class, named person, representing people, defining attribute variables name and sex (name and gender), and defining a method: When sex is male, print he; when sex is female, print she
Refer to the following code:
1 classPerson :2 def __init__(self,name,sex):3Self.name =name4Self.sex =Sex5 6 defPrint_heorshe (self):7 ifSelf.sex = ="male":8 Print("He")9 elifSelf.sex = ="female":Ten Print("She") One AMay = person (" May","female") -Peter = Person ("Peter","male") - the May.print_heorshe () -Peter.print_heorshe ()
When we write the Student class, we can inherit the person class completely, and use class Subclass_name (Baseclass_name) to represent the inheritance;
What are the benefits of inheritance? The biggest benefit is that the subclass obtains the full functionality of the parent class. The Print_heorshe method of the parent class can be used directly as follows student class
When instantiating student, subclasses need to provide the two attribute variables required by the parent class name and sex
1 classPerson :2 def __init__(self,name,sex):3Self.name =name4Self.sex =Sex5 6 defPrint_heorshe (self):7 ifSelf.sex = ="male":8 Print("He")9 elifSelf.sex = ="female":Ten Print("She") One A classStudent (person):#Student inherit person - Pass - theMay = Student (" May","female") -Peter = Student ("Peter","male") - - Print(May.name,may.sex,peter.name,peter.sex) + May.print_heorshe () -Peter.print_heorshe ()
Python Learning (vii) Object-oriented-inheritance and polymorphism