Advanced for python beginners -- detailing inheritance and polymorphism (with code)

Posted by Fizzgig on Mon, 24 Jan 2022 04:53:38 +0100

Reading guide

Handsome fat school is coming again!!!

I've just finished learning java recently. I'm not very proficient in inheritance and polymorphism. I found the inheritance polymorphism of python when I checked the data. I think it's interesting. I'll share it with you. I can compare it with Java.

inherit

What is inheritance

  • Of course, the above figure is just a metaphor. In fact, inheritance in code is a concept in object-oriented software technology. It is the three basic characteristics of object-oriented together with polymorphism and encapsulation. Inheritance can make subclasses have the properties and methods of the parent class, or redefine and append properties and methods. Note: inheritance in python is divided into single inheritance and multiple inheritance
  • The purpose of inheritance is to improve the reuse rate of code and reduce the amount of unnecessary code. The following figure shows the basic characteristics of animals, cats and dogs. Animals are parents and cats and dogs are children

Characteristics of inheritance

  • 1. When calling the method of the base class, you need to prefix the class name of the base class and take the self parameter variable. Unlike calling ordinary functions in classes, you don't need to bring self parameters.

  • 2. In inheritance, the construction of the base class (init() method) will not be called automatically. It needs to be called in the construction of its derived class.

  • 3. Python always looks for the method of the corresponding type first. If it can't find the corresponding method in the derived class, it starts to look for it one by one in the base class. (first find the called method in this class, and then find it in the base class if it cannot be found).

  • 4. Parent class in inheritance: used for the inherited class, which is called parent class, also called base class, or superclass. Subclass: a class that inherits from other classes, called a subclass, also known as a derived class.

Single inheritance

  • python supports class inheritance. If a language does not support inheritance, classes are meaningless. In this regard, I think it's better to look at the actual code in terms of fluency. (personally)
class Animal: #Parent class
    def eat(self): 
        print("-----eat-----")

    def drink(self):
        print("-----drink-----")
        
    def sleep(self):
        print("-----sleep-----")


class Dog(Animal): #The subclass inherits the parent class
    """
    def eat(self):
        print("-----eat-----")

    def drink(self):
        print("-----drink-----")
     
     def sleep(self):
        print("-----sleep-----")
    """
    pass


class Cat:
    pass


wang_cai = Dog()
wang_cai.eat()
wang_cai.drink()
wang_cai.sleep()#wang cai inherited the eating, drinking and sleeping of animals

Multilayer inheritance


Simply put, it is such a relationship: a subclass of animal dog Xiaotian dog (which is becoming more and more specific) inherits the parent class and then is inherited by other subclasses

class Animal:
    def eat(self):
        print("-----eat-----")

    def drink(self):
        print("-----drink-----")


class Dog(Animal):
    def bark(self):
        print("-----Wang Wang barking------")


class XTQ(Dog):
    """Defines an asthmatic dog"""
    pass
#After inheritance, the howling dog will "eat", "drink" and "bark"

rewrite

As the name suggests, it is to rewrite the method, but: the method name is unchanged

For example:

class Animal: #Parent class
    def eat(self):
        print("-----eat-----")

    def drink(self):
        print("-----drink-----")

 
class Dog(Animal): 
    def bark(self):
        print("-----Wang Wang barking------")


class XTQ(Dog): #Override Dog method
    """Defines an asthmatic dog"""
    def bark(self):
        print("----Howl-----")
#Rewritten Barker

Multiple inheritance


This picture clearly expresses the meaning of multi inheritance. An animal inherits penguin and erha at the same time

The following code:

# Define a parent class
class qi-e:
    def printA(self):
        print('----penguin----')

# Define a parent class
class er-ha:
    def printB(self):
        print('----Erha----')

# Define A subclass that inherits from A and B
class C(A,B):
    def printC(self):
        print('----I don't know what it is----')

obj_C = C()
obj_C.printA()
obj_C.printB()

polymorphic

  • Function: let functions with different functions use the same function name, so that functions with different contents (functions) can be called with one function name.
  • Features: only care about whether the instance method of the object has the same name, not the type of the object; The inheritance relationship between the classes to which the object belongs is optional; The benefits of polymorphism can increase the flexibility of external calls of the code, make the code more general and have strong compatibility; Polymorphism is a technique for calling methods and will not affect the internal design of classes.
class Duck:
    def quack(self):
        print("Quaaaaaack!")


class Bird:
    def quack(self):
        print("bird imitate duck.")


class Doge:
    def quack(self):
        print("doge imitate duck.")


def in_the_forest(duck):
    duck.quack()


duck = Duck()
bird = Bird()
doge = Doge()
for x in [duck, bird, doge]:
    in_the_forest(x)

expand:

  • Expression of polymorphism in Java: polymorphism can be understood as multiple forms of a thing. Similarly, polymorphism is also supported in Python, but polymorphism is limited. The main reason is that the use of variables in Python does not need to be declared, so there is no polymorphism embodiment that the parent class reference points to the child class object, and python does not support overloading. The use of polymorphism in Python is not as obvious as that in Java, so deliberately talking about polymorphism in Python is not of great significance.

summary

I think you can use a language whenever it's convenient. Inheritance and polymorphism in java and python have their own advantages. You can rest assured when using them. At the same time, you can also remember them by comparison. It's not just that you can speak a language, but you'd better learn more. If you use it, you can save your life.

thank you!!!
In addition, let's first mention that fat school is preparing to build a front-end and back-end system in the summer vacation. If there is enough time to write a python and then a java, after all, it is necessary to take the postgraduate entrance examination. This may be the last large-scale practice. At that time, I hope you will give more support. Thank you 😃

Topics: Python Class Polymorphism