The content shared with you in this article is about Python object-oriented inheritance and polymorphism. It has certain reference value. Friends in need can refer to it
In OOP programming, when we define A class can inherit from an existing class. The new class is called a subclass (Subclass), and the inherited class is called a base class, parent class, or super class (Base class, Supper class).
For example, we have written a class named Animal, and there is a run() method that can print directly:
class Animal(object):
def run(self):
print('Animal is running...')When we need to write Dog and Cat classes, we can directly print from Animal class inheritance:
class Dog(Animal):
pass
class Cat(Animal):
passFor Dog, Animal is its parent class, and for Animal, Dog is its subclass. Cat and Dog are similar.
What are the benefits of inheritance? The biggest advantage is that the subclass obtains all the functions of the parent class. Since Animal implements the run() method, Dog and Cat, as its subclasses, automatically have the run() method without doing anything:
dog = Dog() dog.run() cat = Cat() cat.run()
Animal is running... Animal is running...
Of course, you can also add subclasses Some methods, such as Dog class.
The second benefit of inheritance requires us to make a little improvement to the code. You see, whether it is Dog or Cat, when they run(), they display Animal is running.... The logical way is to display Dog is running... and Cat is running... respectively, so , the improvements to the Dog and Cat classes are as follows:
class Animal(object):
def run(self):
print('Animal is running...')class Dog(Animal):
def run(self):
print('Dog is haha running...')
def eat(self):
print('Eating meat...')
class Cat(Animal):
def run(self):
print('Cat is miaomiao running...')
def eat(self):
print('Eating fish...')dog = Dog()
dog.run()
dog.eat()
cat = Cat()
cat.run()
cat.eat()再次运行,结果如下:
Dog is haha running... Eating meat... Cat is miaomiao running... Eating fish...
When the same run() method exists in both the subclass and the parent class, we say that the run() of the subclass overrides the run of the parent class. (), when the code is running, the subclass's run() will always be called. In this way, we get another benefit of inheritance: polymorphism.
To understand what polymorphism is, we first need to explain a little more about data types. When we define a class, we actually define a data type. The data types we define are no different from the data types that come with Python, such as str, list, and dict:
a = list()#a是list类型#a是list类型 b = Animal() #b是Animal类型 c = Dog #c是Dog类型
To determine whether a variable is a certain type, you can use isinstance() to determine:
>>> isinstance(a, list) True >>> isinstance(b, Animal) True >>> isinstance(c, Dog) True
It seems that a, b, and c do correspond to the three types of list, Animal, and Dog.
But wait, try:
>>> isinstance(c, Animal) True
It seems that c is not only Dog, c is also Animal!
But if you think about it carefully, this makes sense, because Dog inherits from Animal. When we create an instance c of Dog, we think that the data type of c is Dog. But it’s not wrong that c is also Animal. Dog is originally a type of Animal!
So, in the inheritance relationship, if the data type of an instance is a subclass, its data type can also be regarded as the parent class. However, the reverse is not true:
>>> b = Animal() >>> isinstance(b, Dog) False
Dog can be regarded as Animal, but Animal cannot be regarded as Dog.
To understand the benefits of polymorphism, we need to write another function that accepts a variable of type Animal:
def run_twice(animal):
animal.run()
animal.run()When we pass in an instance of Animal, run_twice() Print out:
>>> run_twice(Animal()) Animal is running... Animal is running...
When we pass in the instance of Dog, run_twice() prints out:
>>> run_twice(Dog()) Dog is running... Dog is running...
It doesn’t seem interesting, but if we think about it carefully, if we then Define a pig type, also derived from Animal:
class Pig(Animal):
def run(self):
print('Pig is running slowly...')When we call run_twice(pig())
>>> run_twice(Pig()) Pig is running slowly... Pig is running slowly...
The advantage of polymorphism is that when we need to pass in Dog, Cat, Pig , we only need to receive the Animal type, because Dog, Cat, and Pig are all Animal types, and then operate according to the Animal type. Since the Animal type has a run() method, any type passed in, as long as it is an Animal class or subclass, will automatically call the run() method of the actual type. This is the meaning of polymorphism:
For a variable, we only need to know that it is of type Animal, without knowing exactly its subtype, we can safely call the run() method, and whether the specific call of the run() method works on Animal, Dog, cat, or Pig On the object, it is determined by the exact type of the object at runtime. This is the real power of polymorphism: the caller only cares about the call, regardless of the details. When we add a new subclass of Animal, we only need to ensure that the run() method is written Correct, regardless of how the original code is called. This is the famous "open and closed" principle:
Closed to modification: There is no need to modify functions such as run_twice() that rely on the Animal type.
Inheritance can also be inherited level by level. Any class can ultimately be traced back to the root class object. These inheritance relationships look like an inverted tree:

Related recommendations:
Python object-oriented access restrictions
Python object-oriented classes and examples
##
The above is the detailed content of Python object-oriented inheritance and polymorphism. For more information, please follow other related articles on the PHP Chinese website!
Python: Automation, Scripting, and Task ManagementApr 16, 2025 am 12:14 AMPython excels in automation, scripting, and task management. 1) Automation: File backup is realized through standard libraries such as os and shutil. 2) Script writing: Use the psutil library to monitor system resources. 3) Task management: Use the schedule library to schedule tasks. Python's ease of use and rich library support makes it the preferred tool in these areas.
Python and Time: Making the Most of Your Study TimeApr 14, 2025 am 12:02 AMTo 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: Games, GUIs, and MoreApr 13, 2025 am 12:14 AMPython 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 vs. C : Applications and Use Cases ComparedApr 12, 2025 am 12:01 AMPython 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.
The 2-Hour Python Plan: A Realistic ApproachApr 11, 2025 am 12:04 AMYou 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: Exploring Its Primary ApplicationsApr 10, 2025 am 09:41 AMPython 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.
How Much Python Can You Learn in 2 Hours?Apr 09, 2025 pm 04:33 PMYou 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 in project and problem-driven methods within 10 hours?Apr 02, 2025 am 07:18 AMHow 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...


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

Dreamweaver Mac version
Visual web development tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),






