In OOP programming, when we define a class, we can inherit from an existing class, and the new class is called a subclass (subclass), and the inherited class is called the base class, the parent class, or the superclass (base-Class, Super-Class).
For example, we have written a class named Animal
, and there is a run()
way to print it directly:
class Animal(object): def run(self): print ‘Animal is running...‘
When we need to write the dog and cat classes, we can inherit directly from the animal class:
class Dog(Animal): passclass Cat(Animal): pass
For dog, Animal is its parent class, and for animal, dog is its subclass. Cat and dog are similar.
What are the benefits of inheritance? The biggest benefit is that the subclass obtains the full functionality of the parent class. Since animial implements the run()
method, dog and cat, as its subclasses, automatically have the method if nothing is done run()
:
dog = Dog()dog.run()cat = Cat()cat.run()
The results of the operation are as follows:
Animal is running...Animal is running...
Of course, you can also add some methods to the subclass, such as the Dog class:
class Dog(Animal): def run(self): print ‘Dog is running...‘ def eat(self): print ‘Eating meat...‘
The second benefit of inheritance requires a little improvement in our code. You see, both dog and cat, when they are, they show that the run()
Animal is running...
logical approach is to show separately Dog is running...
and Cat is running...
, therefore, improvements to the dog and cat classes are as follows:
class Dog(Animal): def run(self): print ‘Dog is running...‘class Cat(Animal): def run(self): print ‘Cat is running...‘
Run again and the results are as follows:
Dog is running...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.
To understand what polymorphism is, let's start with a little more explanation of the data type. When we define a class, we actually define a data type. The data types we define are the same data types that python comes with, such as STR, list, dict:
a = list() # a是list类型b = Animal() # b是Animal类型c = Dog() # c是Dog类型
Judging whether a variable is a type can be isinstance()
judged by:
>>> isinstance(a, list)True>>> isinstance(b, Animal)True>>> isinstance(c, Dog)True
It seems that a, B and C do correspond to the list, Animal, dog 3 types.
But wait, try it:
>>> isinstance(c, Animal)True
Looks like C's not just dog,c or animal!.
But it makes sense to think about it, because dog is inherited from animal, and when we create an instance of dog, c
we think c
the data type is dog, but it is also c
animal, right, Dog is a kind of animal!
So, in an inheritance relationship, if the data type of an instance is a subclass, its data type can also be considered a parent class. However, the reverse is not possible:
>>> b = Animal()>>> isinstance(b, Dog)False
Dog can be regarded as animal, but animal can not be regarded as dog.
To understand the benefits of polymorphism, we also need to write a function that takes a variable of type animal:
def run_twice(animal): animal.run() animal.run()
When we pass in an instance of animal, we run_twice()
print out:
>>> run_twice(Animal())Animal is running...Animal is running...
When we pass in the instance of dog, we run_twice()
print out:
>>> run_twice(Dog())Dog is running...Dog is running...
When we pass in an instance of cat, we run_twice()
print out:
>>> run_twice(Cat())Cat is running...Cat is running...
It doesn't seem to mean anything, but think about it now, if we define a tortoise type again, it's derived from animal:
class Tortoise(Animal): def run(self): print ‘Tortoise is running slowly...‘
When we call Run_twice (), an instance of the tortoise is passed in:
>>> run_twice(Tortoise())Tortoise is running slowly...Tortoise is running slowly...
You will find that a new subclass of animal is not necessary to make any changes to Run_twice (), in fact, any function or method that relies on animal as a parameter can run without modification, because of polymorphism.
The advantage of polymorphism is that when we need to pass in dog, Cat, tortoise ... , we only need to receive the animal type, because dog, Cat, tortoise ... are animal types, and then follow the animal type. Because the animal type has run()
methods, any type passed in, as long as it is a animal class or subclass, will automatically invoke the actual type of run()
method, which is the meaning of polymorphism:
For a variable, we only need to know that it is a animal type, without having to know exactly what its subtype is, you can safely invoke run()
the method, and the run()
method is called on the animal, Dog, cat, or Tortoise object. Determined by the exact type of the object at run time, this is the true power of polymorphism: The caller just calls, regardless of the details, and when we add a animal subclass, simply make sure that the run()
method is written correctly, regardless of how the original code is called. This is the famous "opening and shutting" principle:
Open to extensions: Allow new animal subclasses;
Closed for modification: You do not need to modify such functions as the dependent animal type run_twice()
.
Inheritance can also be inherited from the first level, like from Grandpa to father, and then to the son of the relationship. And any class, in the end, can be traced back to the root class object, which looks like a backward tree. For example, the following inheritance tree:
Summary
Inheritance can take all the functions of the parent class directly, so that you do not have to re-zero, subclasses only need to add their own unique methods, but also the parent class does not fit the method overrides overrides;
With inheritance, you can have polymorphism. When invoking the class instance method, as far as possible the variable as the parent class type, so that all subclass types can be properly received;
The old way of defining a Python class allows for not inheriting from the object class, but this programming is heavily deprecated. At any time, if no suitable class can inherit, it inherits from the object class.
Python Inheritance and polymorphism