Python Object-Oriented Programming inheritance and polymorphism explanation, python Object-Oriented Programming

Source: Internet
Author: User

Python Object-Oriented Programming inheritance and polymorphism explanation, python Object-Oriented Programming

This article describes the inheritance and Polymorphism of Python object-oriented programming. We will share this with you for your reference. The details are as follows:

Python class inheritance

In Object Oriented Programming, when we define a class, we can inherit from an existing class. The new class is called Subclass ), the inherited class is called the Base class, parent class, or Super class ).

Let's first define a class Person, which represents a Person and defines the property variables name and sex (name and gender );

Define a method print_title (): print man when sex is male; print woman when sex is female. Refer to the following code:

Class Person (object): def _ init _ (self, name, sex): self. name = name self. sex = sex def print_title (self): if self. sex = "male": print ("man") elif self. sex = "female": print ("woman") class Child (Person): # Child inherits Person passMay = Child ("May", "female ") peter = Person ("Peter", "male") print (May. name, May. sex, Peter. name, Peter. sex) # subclass inherits the methods and attributes of the parent class. print_title () Peter. print_title ()

The Child class can inherit the Person class (Child is Person), and use class subclass_name (baseclass_name) to represent inheritance;

What are the benefits of inheritance? The biggest benefit is that the subclass obtains all attributes and functions of the parent class. The following Child class can directly use the print_title () method of the parent class.

When the Child class is instantiated, the Child class inherits the constructor of the parent class, and you need to provide the two Property variables name and sex required by the parent class Person:

In the inheritance relationship, if the data type of an instance is a subclass, it can also be considered as a parent class (May is both Child and Person ). However, in turn, it won't work (Peter is only Person, not Child ).

Inheritance can also be inherited at the first level, just like the relationship from grandpa to dad and then to son. In the end, any class can be traced back to the root class object. These inheritance relationships look like a falling tree. For example, the following inheritance tree:

Isinstance () and issubclass ()

The difference between Python and other languages is that when we define a class, we actually define a data type. The defined data types are the same as those of Python, such as str, list, And dict.

Python has two inherited functions: isinstance () is used to check the instance type, and issubclass () is used to check class inheritance. See the following example:

Class Person (object): passclass Child (Person): # Child inherits Person passMay = Child () Peter = Person () print (isinstance (May, Child )) # Trueprint (isinstance (May, Person) # Trueprint (isinstance (Peter, Child) # Falseprint (isinstance (Peter, Person) # Trueprint (issubclass (Child, Person )) # True

Python class Polymorphism

Before explaining what polymorphism is, we re-write the print_title () method in the Child class: male, print boy; female, print girl

Class Person (object): def _ init _ (self, name, sex): self. name = name self. sex = sex def print_title (self): if self. sex = "male": print ("man") elif self. sex = "female": print ("woman") class Child (Person): # Child inherits Person def print_title (self): if self. sex = "male": print ("boy") elif self. sex = "female": print ("girl") May = Child ("May", "female") Peter = Person ("Peter", "male ") print (May. name, May. sex, Peter. name, Peter. sex) May. print_title () Peter. print_title ()

When both the subclass and the parent class have the same print_title () method, the print_title () method of the subclass overwrites the print_title () method of the parent class. When the code is running, print_title () of the subclass is called ()

In this way, we get another benefit of inheritance: polymorphism.

The advantage of polymorphism is that when we need to input more sub-classes, such as new Teenagers and Grownups, we only need to inherit the Person type, while print_title () the method either directly does not overwrite (that is, using Person), or can overwrite a unique one. This is what polymorphism means. The caller only calls the object, regardless of the details. When we add a Person subclass, we only need to ensure that the new method is correctly written without worrying about the original code. This is the famous "open and closed" principle:

Open for extension: Allows subclasses to override method functions.

Closed for modification: directly inherits the parent class method function without rewriting.

Subclass rewrite Constructor

The subclass can have no constructor, indicating that the constructor is consistent with the parent class. The subclass can also rewrite the constructor. Now, we need to add two Property variables in the Child class: mother and father, we can construct the following (we recommend that the subclass call the construction method of the parent class, refer to the subsequent code ):

Class Person (object): def _ init _ (self, name, sex): self. name = name self. sex = sexclass Child (Person): # Child inherits Person def _ init _ (self, name, sex, mother, father): self. name = name self. sex = sex self. mother = mother self. father = fatherMay = Child ("May", "female", "Jun L", "June") print (May. name, May. sex, May. mother, May. father)

If the parent class constructor contains many attributes, you only need to add one or two sub-classes, and there will be a lot of redundant code. Here, the sub-classes can call the constructor of the parent class, as shown below:

Class Person (object): def _ init _ (self, name, sex): self. name = name self. sex = sexclass Child (Person): # Child inherits Person def _ init _ (self, name, sex, mother, father): Person. _ init _ (self, name, sex) # The subclass calls self to the constructor of the parent class. mother = mother self. father = fatherMay = Child ("May", "female", "Jun L", "June") print (May. name, May. sex, May. mother, May. father)

Multi-Inheritance

The concept of multi-inheritance should be better understood. For example, if you need to create a new class baby to inherit Child, you can inherit the attributes and methods of the parent class and the parent class upper class, use the method of layer class proximity first. The Code is as follows:

Class Person (object): def _ init _ (self, name, sex): self. name = name self. sex = sex def print_title (self): if self. sex = "male": print ("man") elif self. sex = "female": print ("woman") class Child (Person): passclass Baby (Child): passMay = Baby ("May", "female ") # inherit the print (May. name, May. sex) May. print_title () # class Child (Person): def print_title (self): if self. sex = "male": print ("boy") elif self. sex = "female": print ("girl") class Baby (Child): passMay = Baby ("May", "female") May. print_title () # use upper-layer classes first

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.