How to understand polymorphism in python
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code is available on Mac. It has powerful extensions, Git integration, terminal and debugger, and also offers a wealth of setup options. However, for particularly large projects or highly professional development, VS Code may have performance or functional limitations.

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

The key to running Jupyter Notebook in VS Code is to ensure that the Python environment is properly configured, understand that the code execution order is consistent with the cell order, and be aware of large files or external libraries that may affect performance. The code completion and debugging functions provided by VS Code can greatly improve coding efficiency and reduce errors.
