Python polymorphic sample code in the Python learning manual

Source: Internet
Author: User
When dealing with polymorphic objects, just pay attention to its interface, Python does not need to display the writing (like Java) interface, in the use of objects first assumed that the interface, if not actually included, in the run error.

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 the gun, it is believed that it has the function of firing, if there is no fire function, the program operation in the error * * *
Gun.fire ()

As you can see, Python is not at the language level to ensure the correctness of the interface, but only with the documentation and code (you can check the presence of the interface in the code, HASATTR (Gun, ' fire '), compared to the normal static language.

  • Related Article

    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.