The classes in object-oriented programming have three main features: inheritance , encapsulation , polymorphism
inheritance : creating specialized class objects based on common classes
Encapsulation : working details of hidden objects in the external world
polymorphic: You can use the same action for objects of different classes
The basic form of a class's inheritance definition in Python is as follows:
# Parent Class class superclassname: block# Subclass class Subclassname (superclassname ): block
Description: When defining a class, you can immediately follow the class name with a pair of parentheses, specifying the inherited parent class in parentheses, and if there are more than one parent class, separate the names of the parent classes with commas.
classUniversitymember: # defines a parent class Universitymember def __init__(self,name,age): Self.name=name Self.age= AgedefGetName (self):returnSelf.namedefgetage (self):returnSelf.ageclassStudent (Universitymember): # defines a subclass Student def __init__(Self,name,age,sno,mark): Universitymember.__init__(Self,name,age)# Note To display the call to the parent class constructor method, and pass the argument selfSelf.sno =Sno # Student class has sno,mark two properties Self.mark=MarkdefGetsno (self):returnSelf.snodefGetmark (self):returnSelf.markclassTeacher (Universitymember): # defines a subclass Teacher def __init__(self,name,age,tno,salary): Universitymember.__init__(self,name,age) Self.tno=TNO # Teacher class has tno,salary two properties self.salary=SalarydefGettno (self):returnSelf.tnodefgetsalary (self):returnSelf.salary
As you can see from the code above:
1) in Python, if the parent class and subclass both redefine the constructor method __init () __, when the subclass is instantiated, the constructor of the subclass does not automatically invoke the constructor of the parent class, and the call must be displayed in the subclass.
2) If you need to call a method of a parent class in a subclass, you need to use the parent class name. This method is called in this way, and when called in this way, note that the self parameter is passed in the past.
For an inheritance relationship, the subclass inherits all of the public properties and methods of the parent class, can be called through the parent class name in the subclass, and for private properties and methods, the subclass is not inherited, so it cannot be accessed by the parent class name in the subclass.
Python Learning Summary 5: Encapsulation, inheritance, polymorphism