Using examples to explain the concepts of inheritance and polymorphism in Python _python

Source: Internet
Author: User
Tags instance method in python

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 a base class, a parent class, or a superclass (base class, Super Class).

For example, we have written a class called Animal, and a run () method can be printed directly:

Class Animal (object):
  def run (self):
    print ' Animal is running ... '

When we need to write dog and cat classes, we can inherit directly from the animal class:

Class Dog (Animal):
  Pass

class 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 subclasses get the full functionality of the parent class. Because Animial implements the run () method, Dog and cat, as its subclasses, do nothing, automatically owning the run () method:

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, whether it's dog or cat, when they run (), they show the animal is running ..., the logical approach is to show dog is running separately ... 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, the results are as follows:

Dog is running
... Cat is running ...

When both the subclass and the parent have the same run () method, we say that the run () of the subclass overrides the run () of the parent class and always invokes the subclass's run () when the code is run. In this way, we gain another benefit of inheritance: polymorphism.

To understand what polymorphism is, we first need to give a little more explanation of the data type. When we define a class, we actually define a data type. The data types we define and Python's own data types, such as STR, list, and dict, are no different:

A = List () # A is the list type
b = Animal () # B is the Animal type
c = Dog () # C is the Dog type

Determining whether a variable is a type can be judged by isinstance ():

>>> isinstance (A, list)
true
>>> isinstance (b, Animal)
true
>>> Isinstance (c, Dog)
True

It seems that a, B and C do correspond to the 3 types of list, Animal, and dog.

But wait, try it:

>>> isinstance (c, Animal)
True

It seems that C is more than Dog,c or animal!.

But think about it, it makes sense, because dog is inherited from animal, when we created a dog instance C, we think the data type of C is dog Yes, but C is also animal is also true, dog is animal is a kind of!

Therefore, 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 that's not the opposite:

>>> 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 accepts a variable of type animal:

def run_twice (animal):
  animal.run ()
  Animal.run ()

When we pass in the animal instance, Run_twice () prints out:

>>> Run_twice (Animal ())
Animal is running ...
Animal is running ...

When we pass in the dog instance, Run_twice () prints out:

>>> Run_twice (Dog ())
Dog is running ...
Dog is running ...

When we pass in the instance of Cat, Run_twice () prints 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, we derive from animal:

Class Tortoise (Animal):
  def run (self):
    print ' tortoise is running slowly ... '

When we call Run_twice (), we pass in an instance of tortoise:

>>> Run_twice (Tortoise ())
tortoise is running slowly ...
Tortoise is running slowly ...

You will find that adding a subclass of animal does not necessarily make any changes to Run_twice (), in fact, any function or method that relies on animal as a parameter can operate without modification because of polymorphism.

The advantage of polymorphism is that when we need to pass in dog, Cat, tortoise ... , we just have to receive the animal type, because dog, Cat, tortoise ... Are all animal types, and then follow the animal type. Because the animal type has the run () method, any type passed in, as long as it is a animal class or subclass, automatically invokes the actual type of run () method, which is the meaning of polymorphism:

For a variable, we just need to know that it is a animal type, and you can safely invoke the run () method without knowing its subtype exactly, and the specific call run () method acts on animal, Dog, cat, or tortoise objects. Determined by the exact type of the object at runtime, this is the true power of polymorphism: The caller just calls, regardless of the details, and when we add a subclass of animal, make sure that the run () method is written correctly, regardless of how the original code was invoked. This is the famous "opening and closing" principle:

Open to expansion: Allow new animal subclasses;

Closed for modification: You do not need to modify functions such as run_twice () that depend on the animal type.

Inheritance can also be inherited at the first level, like a relationship from grandpa to father to son. And any class, which eventually goes back to the root class object, looks like an inverted 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 do zero, subclasses only need to add their own unique methods, or the parent class is not appropriate to override the method;

There is the inheritance, can have polymorphism. When invoking a class instance method, try to treat the variable as the parent class type, so that all subclass types can be received properly;

The old way of defining the Python class allows you to not inherit from the object class, but this programming method has been severely deprecated. At any time, if no suitable class can be inherited, it inherits from the object class.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.