Python's object-oriented inheritance and polymorphism

Source: Internet
Author: User
This article to share the content is about the Python object-oriented inheritance and polymorphism, has a certain reference value, the need for friends can refer to

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, Supper Class).

For example, we have written a class named Animal, and there is a run () method to print 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 animal 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 ()
Animal is running ... Animal is running ...

Of course, you can also add some methods to the subclass, such as the Dog class.

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 Animal (object):    def run:        print (' Animal is running ... ') class Dog (Animal):    def run (self)        : Print (' Dog is haha running ... ')    def Eat (self):        print (' Eating meat ... ') class Cat (Animal):    def run (self):        print (' Cat is Miaomiao running ... ')    def Eat (self):        print (' Eating fish ... ') dog = Dog () dog.run () dog.eat () Cat = Cat () Cat.run () cat.eat ()
Run again and the results are as follows:
Dog is haha running ... Eating meat ... Cat is Miaomiao running ... Eating Fish ...

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是list类型 #a is list type B = Animal () #b是Animal类型c = Dog #c是Dog类型

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,c does correspond to the 3 types of list, Animal, and dog.

But wait, try it:

>>> isinstance (c, Animal) True

Looks like C's not just dog,c or animal!.

But think it makes sense, because dog is inherited from animal, and when we create an instance of dog C, we think the data type of C is dog. But C also animal is also true, 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, 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 ...

It doesn't seem to mean anything, but think about it, if we define a pig type again, it's derived from animal:

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

When we call Run_twice (Pig ())

>>> Run_twice (Pig ()) pig is running slowly ... Pig is running slowly ...

The advantage of polymorphism is that when we need to pass in dog, cat, pig, we just have to receive the animal type, because dog, cat, pig 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, will automatically invoke the actual type of the run () method, which is polymorphic meaning:

For a variable, we just need to know that it is a animal type, without knowing exactly what its subtype is, you can safely call the run () method, and the specific call to run () method is on the animal, Dog, cat, or pig 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 subclass of animal, simply make sure that the run () method is written correctly and does not control how the original code is invoked. This is the famous "opening and shutting" principle:

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 primary level. And any class, eventually, can be traced back to the root class object, which looks like a backward tree:


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.