Python sample code _python in the Python learning manual

Source: Internet
Author: User

When dealing with polymorphic objects, you only need to focus on its interface, Python does not need to display the written (like Java) interface, in the use of objects to assume the use of the interface, if not actually included, in the run error.

Copy Code code 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

Copy Code code as follows:

FA = gunfactory (handgun)
Gun = Fa.produce ()

* * As long as it is a gun, it is considered to have the function of firing, if there is no fire function, the program will be in operation of the error * *
Gun.fire ()

You can see that Python does not have the language level to guarantee the correctness of the interface, as opposed to the normal static language, and can only rely on documents, code to ensure that the interface exists in the code, HASATTR (Gun, ' fire '))

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.