Python does not support polymorphism, nor does it need to support polymorphism. Python is a polymorphic language and advocates duck typing. The effective semantics of an object are determined not by inheriting from a specific class or implementing a specific interface, but by the current set of methods and properties.
Polymorphism
is a technique that allows a parent object to be set equal to one or more of its child objects, such as Parent:=Child; More Morphism makes it possible to use pointers of the same class (base class) to reference objects of different classes, and to perform the same operation in different ways depending on the referenced objects.
Related recommendations: "python video tutorial"
class A: def prt(self): print("A") class B(A): def prt(self): print("B") class C(A): def prt(self): print("C") class D(A): pass class E: def prt(self): print("E") class F: pass def test(arg): arg.prt() a = A() b = B() c = C() d = D() e = E() f = F() test(a) test(b) test(c) test(d) test(e) test(f) 输出结果 A B C A E Traceback (most recent call last): File "D:/Python/多态1.py", line 45, in <module> test(f) File "D:/Python/多态1.py", line 30, in test arg.prt() AttributeError: 'F' object has no attribute 'prt' Process finished with exit code 1
At first glance it seems that python supports polymorphism, calling test(a), test(b), test(c ), test(d) works very well, but the following is very different.
When calling test(e), python only calls the prt method of e, and does not determine whether e is an object of the A subclass (in fact, the type of the parameter is not specified when the test method is defined, and python cannot determine it at all).
An error occurs when calling test(f). The reason is very simple. f does not have a prt method.
First of all, Python does not support polymorphism, nor does it need to support polymorphism. Python is a polymorphic language and advocates duck typing. The following is a discussion of duck typing from Wikipedia:
In programming, duck typing (English: duck typing) is a style of dynamic typing. In this style, the effective semantics of an object are determined not by inheriting from a specific class or implementing a specific interface, but by the current set of methods and properties. The name of this concept comes from the duck test proposed by James Whitcomb Riley. The "duck test" can be expressed like this:
"When you see a bird that walks like a duck, swims like a duck, and quacks like a duck, then the bird can be called a duck."
In duck typing, the focus is not on the type of object itself, but on how it is used. For example,
In a language that does not use duck typing, we can write a function that accepts an object of type duck and calls its walk and bark methods.
In a language using duck typing, such a function can accept an object of any type and call its walk and call methods. If the methods that need to be called do not exist, a runtime error will be raised. The fact that any object with the correct walk and call methods can be accepted by a function leads to the above statement, hence the name of this way of determining types.
Duck typing often benefits from not testing the types of parameters in methods and functions, but instead relying on documentation, clear code, and testing to ensure correct usage. Users moving from statically to dynamically typed languages often attempt to add some static (before runtime) type checking, thus compromising the benefits and scalability of duck typing and constraining the dynamic nature of the language.
There is no doubt that an object in python is also a piece of memory. In addition to attributes and methods, the memory also contains the type of the object. We access the object through references, such as a=A(). First, python Create an object A, then declare a variable a, and then associate the variable a with the object A. Variable a has no type, its type depends on its associated object. When a=A(), a is a reference of type A. We can say that a is of type A. If a is assigned a value of 3 and a=3, a is an integer reference, but python is not weak. Type language, in python '2' 3 will report an error, while in PHP '2' 3 will get 5. It can be understood that variables in python are similar to pointers in c. The difference from c is that variables in python can point to any type. Although it is not accurate to say this, it is easier to understand.
Therefore, during the running of python, the type of the parameter is not known before the parameter is passed. Although the method in python is also late binding, it is different from the polymorphic late binding in Java. In Java Late binding at least knows the type of the object, but python does not know the type of the parameter.
The test method only stipulates that it receives one parameter and calls the prt method of this parameter. When running, if this parameter has a prt method, python will execute it. If not, python will report an error, because abcde has a prt method, but f does not, so the above result is obtained. This is how python runs.
The above is the detailed content of How to understand 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

Dreamweaver CS6
Visual web development tools

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.

SublimeText3 Linux new version
SublimeText3 Linux latest version

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

WebStorm Mac version
Useful JavaScript development tools