Home  >  Article  >  Backend Development  >  Taking stock of inheritance and polymorphism in Python

Taking stock of inheritance and polymorphism in Python

Go语言进阶学习
Go语言进阶学习forward
2023-07-25 15:14:56923browse

1. Introduction to inheritance

Inheritance is a way to create a new class. The newly created class is called a subclass, and the inherited class is called a parent class, super class, Base class. The characteristic of inheritance is that subclasses can use the attributes (features, skills) of the parent class. Inheritance is the relationship between classes.

Inheritance can reduce code redundancy and improve reusability.

In real life, inheritance generally refers to children inheriting the property of their parents, as shown below:

Taking stock of inheritance and polymorphism in Python

##2. How to use inheritance?

1. Inheritance syntax

#Class Derived class name (base class name): #The base class name is written in brackets.

In the inheritance relationship, the existing and designed class is called the parent class or base class, and the newly designed class is called the subclass or derived class. A derived class can inherit the public members of the parent class, but cannot inherit its private members.

2. Characteristics of inheritance

  1. In inheritance, the constructor of the base class ( init() method) will not be called automatically, it needs to be called specifically in the construction of its derived class.

  2. If you need to call a base class method in a derived class, use the "base class name. method name ()" method to achieve it, and you need to add the class name prefix of the base class. , and the self parameter variable needs to be brought. Different from calling ordinary functions in a class, there is no need to bring the self parameter. You can also use the built-in function super() for this purpose.

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

3. Single inheritance

3.1 Single inheritance

Example:

class Animal: #父类
    def eat(self): 
        print("-----吃-----")


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




class Dog(Animal): #子类继承父类
    """
    def eat(self):
        print("-----吃-----")


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




class Cat:
    pass




wang_cai = Dog()
wang_cai.eat()
wang_cai.drink()

Run result:

Taking stock of inheritance and polymorphism in Python


3.2 Multi-layer inheritance

Example:

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


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




class Dog(Animal):
    def bark(self):
        print("-----汪汪叫------")




class XTQ(Dog):
    """定义了一个哮天犬 类"""
    pass




class Cat(Animal):
    def catch(self):
        print("----捉老鼠----")




xtq = XTQ()
xtq.eat()
xtq.bark()

Run result:

Taking stock of inheritance and polymorphism in Python


3.3 重写父类方法

例:

class Animal: #父类
    def eat(self):
        print("-----吃-----")


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


 
class Dog(Animal): 
    def bark(self):
        print("-----汪汪叫------")




class XTQ(Dog): #重写Dog方法
    """定义了一个哮天犬 类"""
    def bark(self):
        print("----嗷嗷叫-----")




class Cat(Animal):
    def catch(self):
        print("----捉老鼠----")




xtq = XTQ()
xtq.eat()
xtq.bark()

运行结果:

Taking stock of inheritance and polymorphism in Python


4. 多继承

4.1 多继承

Taking stock of inheritance and polymorphism in Python

从图中能够看出,所谓多继承,即子类有多个父类,并且具有它们的特征。

Python中多继承的格式如下:

# 定义一个父类
class A:
    def printA(self):
        print('----A----')


# 定义一个父类
class B:
    def printB(self):
        print('----B----')


# 定义一个子类,继承自A、B
class C(A,B):
    def printC(self):
        print('----C----')


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

运行结果:

----A----
----B----

Python中是可以多继承的,父类中的方法、属性,子类会继承。


想一想:

如果在上面的多继承例子中,如果父类A和父类B中,有一个同名的方法,那么通过子类去调用的时候,调用哪个?

#coding=utf-8
class base(object):
    def test(self):
        print('----base test----')
class A(base):
    def test(self):
        print('----A test----')


# 定义一个父类
class B(base):
    def test(self):
        print('----B test----')


# 定义一个子类,继承自A、B
class C(A,B):
    pass


obj_C = C()
obj_C.test()


print(C.__mro__) #可以查看C类的对象搜索方法时的先后顺序

运行结果:

Taking stock of inheritance and polymorphism in Python


5. 多态

5.1 什么是多态?

多态的概念是应用于Java和C#这一类强类型语言中,而Python崇尚“鸭子类型”。

所谓多态:定义时的类型和运行时的类型不一样,此时就成为多态。

  • Python伪代码实现Java或C#的多态。

5.2  案例

Python  “鸭子类型”

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)

运行结果:

Taking stock of inheritance and polymorphism in Python


三、总结

本文以生活中的基础现象为切入点,主要介绍了Python基础中继承和多态,包括单继承、多继承的语法、多态常见的 “鸭子类型”、 以及如何重写父类的方法都做了详细的讲解。

The above is the detailed content of Taking stock of inheritance and polymorphism in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:Go语言进阶学习. If there is any infringement, please contact admin@php.cn delete