Python polymorphism sample code in the python Learning Manual

Source: Internet
Author: User
Polymorphism is a basic feature of Object-Oriented Language. polymorphism means that variables do not know what the referenced object is, and different behavior methods are presented based on different referenced objects, the following uses an example to learn how to use it. when dealing with multi-state objects, you only need to pay attention to its interface. in python, you do not need to compile (like Java) interfaces, when using an object, assume that this interface exists. if it is not included, an error is returned during running.

The code is as follows:


Class handGun ():
Def _ init _ (self ):
Pass
Def fire (self ):
Print 'handgun fire'

Class carbine ():
Def _ init _ (self ):
Pass
Def fire (self ):
Print 'carbine fire'

Import handGun
Import carbine
Class gunFactory ():
Def _ init _ (self, gun_type ):
Self. gun_type = gun_type
Def produce (self ):
If handGun = self. gun_type:
Return handGun. handGun ()
Else:
Return carbine. carbine ()

Client

The code is as follows:


Fa = gunFactory (handGun)
Gun = fa. produce ()

/* As long as it is a gun, it is considered to have the function of opening fire. if there is no function of opening fire, an error will be reported when the program is running */
Gun. fire ()

It can be seen that, compared with the general static language, python does not guarantee the correctness of the interface at the language level. it can only be ensured by documents and code (you can check whether the interface exists in the code, hasattr (gun, 'fire '))

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.