Polymorphism in Python

Source: Internet
Author: User
Polymorphism

Is a technology that allows you to set a parent object to be equal to one or more of its sub-objects, such as parent: = Child; polymorphism allows you to use the same class (base class) type pointer to reference objects of different classes, and perform the same operation in different ways according to different referenced objects.

The concept of polymorphism in C ++ is easier to understand.

A parent class pointer or name is allowed to reference a subclass object or an object method. The actually called method is the class type method of the object.

-------------- The above content comes from Baidu Baike ----------------


Python does not support Polymorphism

Python is a dynamic language. The parameter type cannot be determined before being passed in. See the following example:

 
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): passclass E: def PRT (Self): Print "E" Class F: passdef test (ARG): Arg. PRT () A = a () B = B () C = C () d = D () E = E () F = f () test () test (B) test (c) test (d) test (e) test (f)

Output result:

A
B
C
A
E
Traceback (most recent call last ):
File "/users/shikefu678/documents/Aptana Studio 3 workspace/demo. py", Line 33, in <module>
Test (A), test (B), test (C), test (D), test (E), test (f)
File "/users/shikefu678/documents/Aptana Studio 3 workspace/demo. py", line 24, in test
Arg. PRT ()
Attributeerror: F instance has no attribute 'prt'

At first glance, it seems that python supports polymorphism. It works well when calling test (A), test (B), test (C), and test (d), but it is quite different below. When test (e) is called, Python only calls the PRT method of E and does not determine whether E is an object of the subclass. (In fact, no parameter type is specified when the test method is defined, python cannot be determined at all ). An error is reported when test (f) is called. The reason is very simple. F has no PRT method.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.