Explain the concept of inheritance and polymorphism in Python with an example

Source: Internet
Author: User
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 that has a run () method that can be printed 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 run () method if nothing is done:

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:    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 run (), they show the animal is running ..., the logical way is to display the dog is running, respectively ... And cat is running, so improvements to the dog and cat classes are as follows:

Class Dog (Animal):  def run:    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 subclass's run () overrides the Run () of the parent class and always calls the subclass's run () when the code runs. 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 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 list, Animal, dog 3 types.

But wait, try it:

>>> isinstance (c, Animal) True

Looks like C's not just 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 that the data type of C is dog Yes, but C is also animal yes, dog is a 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, Run_twice () prints out:

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

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

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

When we pass in an 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, 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 the run () method, any type passed in, as long as it is a animal class or subclass, will automatically invoke the actual type of the run () method, which is the meaning of polymorphism:

For a variable, we only need to know that it is a animal type, without knowing exactly its subtype, you can safely call the run () method, and the specific call of the run () method is on the animal, Dog, cat or Tortoise object, Determined by the exact type of the object at run time, this is the real 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 functions such as run_twice () that depend on the animal type.

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.

  • 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.