Inheritance is a way of creating new classes in Python, where a new class can inherit one or more parent classes, which can be called a base class or a superclass, and a new class is called a derived class or subclass.
The inheritance of classes in Python is divided into: single inheritance and multiple inheritance
Class ParentClass1: #定义父类
Pass
Class ParentClass2: #定义父类
Pass
Class SubClass1 (PARENTCLASS1): #单继承, the base class is ParentClass1, and the derived class is subclass
Pass
Class SubClass2 (PARENTCLASS1,PARENTCLASS2): #python支持多继承, separate multiple inherited classes with commas
Pass
Class Animal:
"People and dogs are animals, so create a animal base class"
def __init__ (self, name, aggressivity, Life_value):
Self.name = name # people and dogs have their nicknames;
Self.aggressivity = aggressivity
# Both man and dog have their own attack;
Self.life_value = Life_value
# Both humans and dogs have their own health values;
Def eat (self):
Print ('%s is eating '%self.name)
Class Dog (Animal):
Pass
Class Person (Animal):
Pass
Egg = person (' Egon ', 10,1000)
HA2 = Dog (' Erlengzi ', 50,1000)
Egg.eat ()
Ha2.eat ()
Concept of derivation:
Of course, subclasses can also add their own new properties or redefine them here (without affecting the parent class), and it is important to note that once you have redefined your own properties and have the same name as the parent, you will be able to invoke the new attributes when you call them.
In subclasses, the new function property of the same name, when editing functions within the function, it may be necessary to reuse the same function function in the parent class, should be used to call the normal function, namely: class names. Func (), at this point is the same as calling the normal function, so even the self parameter to pass the value.
In Python3, a subclass's method of executing the parent class can also be used directly with the Super method.
>>> class Teacher:
... def __init__ (Self,name,gender):
... self.name=name
... self.gender=gender
... def teach (self):
.. print (' teaching ')
...
>>>
>>> class Professor (Teacher):
... pass
...
>>> p1=professor (' Egon ', ' Male ')
>>> P1.teach ()
Three inheritance of Python's object-oriented learning summary