1 in OOP programming, when we define a class, we can inherit from an existing class, the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base classes, Super Class). For example, we have written a class named Animal
, and there is a run()
way to print it directly.
When we need to write Dog
and Cat
class, we can inherit directly from the Animal
class:
class Dog(Animal): passclass Cat(Animal): pass
For Dog
speaking, Animal
it's the parent class, and for Animal
that, Dog
it's a subclass. Cat
and Dog
similar.
The greatest benefit of inheritance is that the subclass obtains the full functionality of the parent class. Because the Animial
method is implemented, run()
Dog
and Cat
as its subclass, nothing is done, it automatically has the run()
method:
dog = Dog()dog.run()cat = Cat()cat.run()
2
class Dog(Animal): def run(self): print(‘Dog is running...‘)class Cat(Animal): def run(self): print(‘Cat is running...‘)
When both the subclass and the parent class have the same run()
method, we say that the child class run()
overrides the parent class, and the subclass is run()
always called when the code is running run()
. In this way, we gain another benefit of inheritance: polymorphism.
3 When we define a class, we actually define a data type. The data types we define are the same as the data types that python comes with, such as STR, list, Dict. Judging whether a variable is a type can be isinstance()
judged.
4 in an inheritance relationship, if the data type of an instance is a subclass, its data type can also be considered a parent class. But, in turn, it doesn't work.
5 Duck Type:
For a static language, such as Java, if an incoming Animal
type is required, the incoming object must be a Animal
type or its subclass, otherwise the method cannot be called run()
.
For dynamic languages such as Python, the incoming type is not necessarily required Animal
. We just need to make sure that the incoming object has one run()
way to do it:
class Timer(object): def run(self): print(‘Start...‘)
这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。
Python Day 8 (2) Inheritance and polymorphism