This article is an example of Python object-oriented programming of inheritance and polymorphism. Shared for your reference, as follows:
Python Class Inheritance
In OOP (Object Oriented Programming) programming, when we define a class, we can inherit from an existing class, the new class is called a Subclass, and the inherited class is called a Base class, Parent class, or Super class. The new class is called Subclass and the inherited class is called Base class, Parent class or Super class.)
Let's define a class Person, which represents a person, and define the attribute variables name and sex;
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): = name = sex def print_title(self): if == "male": print("man") elif == "female": print("woman") class Child(Person): # Child inherits Person pass May = Child("May","female") Peter = Person("Peter","male") print(,,,) # Subclasses inherit parent class methods and attributes May.print_title() Peter.print_title()
Instead, we write the Child class to inherit from the Person class (Child is Person); use class subclass_name(baseclass_name) to indicate inheritance;
What are the benefits of inheritance? The biggest benefit is that the child class gets all the attributes and functions of the parent class. The following Child class can directly use the print_title() method of its parent class.
When instantiating a Child, the child class inherits the constructor of the parent class and needs to provide the two attribute variables name and sex required by the parent class Person:
In an inheritance relationship, if an instance's datatype is some subclass, then it can also be seen as a parent (May is both Child and Person). However, the reverse is not true (Peter is only Person, not Child).
Inheritance can also be inherited from one level to the next, as if the relationship is from grandfather to father to son. And any class, ultimately, can be traced back to the root class object, these inheritance relationships look like an inverted tree. For example, the following inheritance tree:
isinstance() and issubclass()
Python is different from other languages in that when we define a class, we're actually defining a datatype. The datatypes we define are no different than the datatypes that come with Python, such as str, list, and dict.
Python has two functions for determining inheritance: isinstance() for checking instance types, and issubclass() for checking class inheritance. See the example below:
class Person(object): pass class Child(Person): # Child inherits Person pass May = Child() Peter = Person() print(isinstance(May,Child)) # True print(isinstance(May,Person)) # True print(isinstance(Peter,Child)) # False print(isinstance(Peter,Person)) # True print(issubclass(Child,Person)) # True
Polymorphism in Python Classes
Before we explain what polymorphism is, we rewrite the print_title() method in the Child class: if male, print boy; if female, print girl.
class Person(object): def __init__(self,name,sex): = name = sex def print_title(self): if == "male": print("man") elif == "female": print("woman") class Child(Person): # Child inherits Person def print_title(self): if == "male": print("boy") elif == "female": print("girl") May = Child("May","female") Peter = Person("Peter","male") print(,,,) May.print_title() Peter.print_title()
When the same print_title() method exists in both the subclass and the parent, the subclass's print_title() overrides the parent's print_title(), and when the code runs, it calls the subclass's print_title()
In this way, we gain another benefit of inheritance: polymorphism.
The nice thing about polymorphism is that when we need to pass in more subclasses, such as adding Teenagers, Grownups, etc., we only need to inherit from the Person type, and the print_title() method can be either straight overridden (i.e., using Person's) or overridden a unique one. This is what polymorphism means. The caller just calls it, regardless of the details, and when we add a new subclass of Person, we just make sure the new method is written correctly, regardless of the original code. This is the famous "open-close" principle:
Open for extension:Allow subclasses to override method functions
Closed for modification:No overrides, directly inherits parent class method functions
Subclasses override constructors
A subclass can have no constructor, which means that it is constructed in the same way as its parent; a subclass can also override the constructor; now, we need to add two new attribute variables to the subclass Child, mother and father, and we can construct them as follows (it is recommended that the subclass call the constructor method of the parent, see the code that follows):
class Person(object): def __init__(self,name,sex): = name = sex class Child(Person): # Child inherits Person def __init__(self,name,sex,mother,father): = name = sex = mother = father May = Child("May","female","April","June") print(,,,)
If the parent class constructor contains many attributes, the subclass only needs to add 1 or 2, there will be quite a lot of redundant code, over here, the subclass can make calls to the parent class constructor method, refer to the following:
class Person(object): def __init__(self,name,sex): = name = sex class Child(Person): # Child inherits Person def __init__(self,name,sex,mother,father): Person.__init__(self,name,sex) # Subclass calls to parent class constructor methods = mother = father May = Child("May","female","April","June") print(,,,)
multiple inheritance
The concept of multiple inheritance should be better understood, for example, now you need to create a new class baby inheritance Child, can inherit from the parent class and the parent class attributes and methods of the upper class, giving priority to the use of layer class near the method, the code reference is as follows:
class Person(object): def __init__(self,name,sex): = name = sex def print_title(self): if == "male": print("man") elif == "female": print("woman") class Child(Person): pass class Baby(Child): pass May = Baby("May","female") # Inherit attributes from the parent class above print(,) May.print_title() # Methods of the parent class above may be used class Child(Person): def print_title(self): if == "male": print("boy") elif == "female": print("girl") class Baby(Child): pass May = Baby("May","female") May.print_title() # Prioritize the use of methods from higher-level classes
Readers interested in more Python related content can check out this site's topic: thePython Object-Oriented Programming Introductory and Advanced Tutorials》、《Python Data Structures and Algorithms Tutorial》、《Python Socket Programming Tips Summary》、《Summary of Python function usage tips》、《Summary of Python string manipulation techniques》、《Summary of Python coding manipulation techniquesand thePython introductory and advanced classic tutorials》
I hope that what I have said in this article will help you in Python programming.