1. Concept of inheritance
In real life, inheritance generally refers to the children inherit their parents ' property.
In the program, inheritance describes the relationship between things, such as cats and dogs belong to animals, the program can be described as cats and dogs inherit automatic objects, the same, Persian and Parisian cats are inherited from the cat, and Shar Pei and spotted dogs inherit the dog.
2. Inheritance Example
#define a parent class, as follows:classCat (object):def_init_ (self,name,color="White"): Self.name=name Self.color=ColordefRun (self):Print("%s--running"%self.name)#define a subclass: Inherit the Cat class as follows:classBosi (Cat):defSetnewname (self,newname): Self.name=NewNamedefEat (self):Print("%s--is eating ."%self.name) BS=Bosi ("Indian cat")Print("BS's name is:%s"%bs.name)Print("the color of BS is:%s"%bs.color) bs.eat () Bs.setnewname ("Persian") Bs.run ()
Description
* Although the subclass does not define the _init_ method, but the parent class has, so this method is inherited when the subclass inherits the parent class, so as long as the Bosi object is created, the inherited _init_ method is executed by default.
Summarize:
* Subclass when inheriting, when defining a class, the name of the parent class in parentheses ()
* The parent class's properties, methods, are inherited to subclasses
Note the point:
classAnimal (object):def_init_ (Self,name ='Animal', color ='White') Self._name=name Self.color=Colordef_test (self):Print(Self._name)Print(Self.color)defTest (self):Print(Self._name)Print(Self.color)classDog (Animal):defdogtest (self):#print (self._name) #不能访问到父类的私有属性 Print(Self.color)defDeoTest2 (self):#self._test () #不能访问父类中的私有方法self.test () A=Animal ()#print (a._name) #程序出现异常, cannot access private propertiesPrint(A.color)#a._test () #程序出现异常, cannot access private methoda.test ()Print("-----Split Line-------") D= Dog (name ="Little Flower Dog", color ="Yellow") D.dogtest1 () D.dogtest2 ()
* Private properties that cannot be accessed directly through the object, but can be accessed through methods
* Private methods that cannot be accessed directly by the object
* Private properties, methods, not Quilt class Foundation, also cannot be accessed
* Under normal circumstances, private properties, methods are not disclosed, often used to do internal things, play a safe role.
Inheritance Introduction and single inheritance