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:
##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
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.
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.
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:
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:
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()
运行结果:
4. 多继承
4.1 多继承
从图中能够看出,所谓多继承,即子类有多个父类,并且具有它们的特征。
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类的对象搜索方法时的先后顺序
运行结果:
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)
运行结果:
三、总结
本文以生活中的基础现象为切入点,主要介绍了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!

To maximize the efficiency of learning Python in a limited time, you can use Python's datetime, time, and schedule modules. 1. The datetime module is used to record and plan learning time. 2. The time module helps to set study and rest time. 3. The schedule module automatically arranges weekly learning tasks.

Python excels in gaming and GUI development. 1) Game development uses Pygame, providing drawing, audio and other functions, which are suitable for creating 2D games. 2) GUI development can choose Tkinter or PyQt. Tkinter is simple and easy to use, PyQt has rich functions and is suitable for professional development.

Python is suitable for data science, web development and automation tasks, while C is suitable for system programming, game development and embedded systems. Python is known for its simplicity and powerful ecosystem, while C is known for its high performance and underlying control capabilities.

You can learn basic programming concepts and skills of Python within 2 hours. 1. Learn variables and data types, 2. Master control flow (conditional statements and loops), 3. Understand the definition and use of functions, 4. Quickly get started with Python programming through simple examples and code snippets.

Python is widely used in the fields of web development, data science, machine learning, automation and scripting. 1) In web development, Django and Flask frameworks simplify the development process. 2) In the fields of data science and machine learning, NumPy, Pandas, Scikit-learn and TensorFlow libraries provide strong support. 3) In terms of automation and scripting, Python is suitable for tasks such as automated testing and system management.

You can learn the basics of Python within two hours. 1. Learn variables and data types, 2. Master control structures such as if statements and loops, 3. Understand the definition and use of functions. These will help you start writing simple Python programs.

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

Dreamweaver CS6
Visual web development tools