Eighth: Python Basics _8 Object-oriented and network programming

Source: Internet
Author: User

The content of this article
    1. Interface and Normalization design
    2. Polymorphism and polymorphism
    3. Packaging
    4. Object-oriented Advanced
    5. Exception handling
    6. Network programming

First, interface and normalization of design

1. Definition

(1) Normalization allows the user not to care about the object's class, just to know that these objects have certain functions, which greatly reduces the user's difficulty in using.

(2) Normalization allows high-level external users to handle a collection of objects that are compatible with all interfaces without distinction.

2. Analog interface

#!/usr/bin/env pyhon#encoding:utf-8#auth:yangleiclass Interface:    #定义接口Interface类来模仿接口的概念, There is no interface keyword in Python to define an interface.    def read (self):     #定接口函数read        pass    def write:    #定义接口函数write        passclass Txt (Interface):   #文本, implementation of Read and write    def read (self):        print (' Read method of text data ')    def write:        print (' Write method of text data ') Class Sata (Interface):  #磁盘, implementation of Read and write    def du (self):        print (' Read method of hard drive data ')    def write:        print (' Write method of hard disk data ') class Process (Interface):    def read (self):        print (' Read method of process data ')    def Xie (self):        print (' Write method of Process data ') T=txt () S=sata () p=process () T.read () S.read () P.read ()

Polymorphism and polymorphism of two states

1. Definition

Polymorphism: Multiple forms of the same thing

Polymorphism: You can use instances without regard to the instance type

2. Application

#!/usr/bin/env pyhon#encoding:utf-8#auth:yangleiclass Animal: #同一类事物: Animal    def talk (self):        passclass people ( Animal): #动物的形态之一: Man    def Talk (self):        print (' Say hello ') class Dog (Animal): #动物的形态之二: Dog    def talk (self):        Print (' Say Wangwang ') class Pig (Animal): #动物的形态之三: Pig    def talk (self):        print (' Say Aoao ') class Cat (Animal):    Def talk ("Self"):        print (' Say Miaomiao ') class Bird:    def Talk (self):        print (' Jijiji ') # Polymorphism: can be used without regard to the instance type P1=people () D=dog () P2=pig () C=cat () B=bird () # P1.talk () # D.talk () # P2.talk () # C.talk () # B.talk () Def talk (animal):    animal.talk () #p1. Talk () talk (P1) talk (d) talk (P2) talk (c) talk (b)

3. Benefits of Polymorphism

#!/usr/bin/env pyhon#encoding:utf-8#auth:yanglei#list,str,tuplel=list ([+]) T=tuple (()) s=str (' Hello ') l.__ LEN__ () t.__len__ () s.__len__ () def my_len (obj):    return obj.__len__ () print (My_len (l)) print (My_len (t)) print (My_ Len (s))

Three, Package

1. Definition

(1) Encapsulate the data properties: Hide the properties, and then provide access to the external interface, the key is that we customize some control logic within the interface to strictly control the use of data properties.

(2) Encapsulation function properties: In order to isolate complexity.

2. Application

(1)

#!/usr/bin/env pyhon#encoding:utf-8#auth:yangleiclass People:    def __init__ (self,name,age):        if not Isinstance (NAME,STR):            raise TypeError ('%s must is str '%name)        if not isinstance (age,int):            Raise TypeError ( '%s must is int '%age)        self.__name=name        self.__age=age        def tell_info (self):        print (' < name:%s Age:%s > '% (self.__name,self.__age))    def set_info (self,x,y):        if not isinstance (X,STR):            raise TypeError ('% s must is str '%x)        if not isinstance (y,int):            raise TypeError ('%s must is int '%y)        self.__name=x self        . __age=yp=people ("Yanglei",) P.tell_info () p.set_info ("Yanglei", "+") p.set_info ("Yanglei", +) P.tell_info ()

(2)

(1) Withdrawal is a function, and this function has many functions: card, password authentication, input amount, print bill, take money
(2) For users, only need to know the function of withdrawals, the rest of the functions we can hide, it is obvious that
(3) Isolation of complexity and increased security

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass ATM:    def __card (self):        print (' card ')    def __auth ( Self):        print (' user authentication ')    def __input (self): print        (' Input withdrawal amount ')    def __print_bill (self): print        (' Print Bill ' )    def __take_money (self):        print (' withdrawal ')    def withdraw (self):        self.__card ()        Self.__auth ()        self.__input ()        Self.__print_bill ()        Self.__take_money () A=atm () A.withdraw ()

3.__str__

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass people:    def __init__ (self,name,age,sex):        Self.name=name        self.age=age        self.sex=sex    def __str__ (self): #在对象被打印时触发执行        return ' <name:%s age:%s sex:%s> '% (self.name,self.age,self.sex) p1=people (' Egon ', ', ' Male ') p2=people (' Alex ', ' a ', ' Male ') print (p1) Print (p2)

Four, object-oriented advanced

1.hasattr

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass Foo:    x=1    def __init__ (self,name):        self.name= Name    def F1 (self): print (        ' from F1 ') print (foo.x) #Foo. __dict__[' x ']f=foo (' Yanglei ') print (f.__dict__) print ( F.name) print (f.__dict__[' name ')) print (Hasattr (f, ' name ')) #f. Nameprint (Hasattr (F, ' F1 ') #f. F1print (Hasattr (F, ' X ') ) #f. x

2.setattr

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass Foo:    x=1    def __init__ (self,name):        self.name= Name    def F1 (self): print        ("from F1") print (foo.x) #Foo. __dict__[' x ']f=foo (' Yanglei ') setattr (f, ' age ', 18) # f.age=18x

3.getattr

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass Foo:    x=1    def __init__ (self,name):        self.name= Name    def F1 (self): print (        ' from F1 ') print (foo.x) #Foo. __dict__[' x ']f=foo (' Yanglei ') print (GetAttr (f, ' name ') ) #f. Nameprint (GetAttr (F, ' abc ', none)) #f. Abcprint (GetAttr (F, ' name ', none)) #f. Abcfunc=getattr (F, ' F1 ') #f. F1print ( Func) func ()

4.delattr

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass Foo:    x=1    def __init__ (self,name):        self.name= Name    def F1 (self): print        (' from F1 ') print (foo.x) #Foo. __dict__[' x ']f=foo (' Yanglei ') delattr (f, ' name ') # del F.nameprint (f.__dict__)

5. Application

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass ftpserver:    def __init__ (self,host,port):        self.host= Host        Self.port=port    def run (self): when        True:            cmd=input (' >>: '). Strip ()            if not cmd: Continue            if Hasattr (self,cmd):                func=getattr (Self,cmd)                func ()    def get (self):        print (' Get func ')    def put (self):        print (' put Func ') f=ftpserver (' 192.168.1.2 ', +) F.run ()

V. Exception handling

1. Definition

Exceptions are divided into two types:

(1) Syntax error

(2) Logic error

When to use Try ... except?
The error must occur, but the error condition cannot be predicted

2. Application

(1)

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleitry:    aaaa    print (' ==-==>1 ')    l=[]    l[3]    Print (' ==-==>2 ')    d={}    d[' x ']    print (' ==-==>3 ') except Nameerror as E:    print (e) except Indexerror as E:    print (e) except Keyerror as E:    print (e) except Exception as E:    print (E) Else:    print (' Execute ' When there is no error ') Finally:    print (' Execute with or without error ')

(2)

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiclass yangleiexception (baseexception):    def __init__ (self,msg ):        self.msg=msg    def __str__ (self):        return ' <%s> '%self.msgraise yangleiexception (' Yanglei exception ') )

VI. Network programming

1. Sockets

Service side:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socket# buy mobile phone phone=socket.socket (socket.AF_INET,socket. SOCK_STREAM) #插卡phone. Bind ((' 127.0.0.1 ', 8080)) #开机phone. Listen (5) #等电话链接print (' Server start ... ') conn,client_addr= Phone.accept () # (TCP link, client_addr) print (' link ', conn) print (CLIENT_ADDR) #基于建立的链接, send and receive messages CLIENT_DATA=CONN.RECV (1024) Print (' Client message ', Client_data) Conn.send (Client_data.upper ()) #挂电话链接conn. Close () #关机phone. Close ()

Client:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketphone=socket.socket (socket.AF_INET,socket. Sock_stream) Phone.connect ((' 127.0.0.1 ', 8080)) phone.send (' Hello '. Encode (' Utf-8 ')) SERVER_DATA=PHONE.RECV (1024) Print (' Message of service-side response ', Server_data) phone.close ()

2. Communication cycle

Service side:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketphone=socket.socket (socket.AF_INET,socket. SOCK_STREAM) phone.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) #就是它, add Phone.bind ((' 127.0.0.1 ', 8080)) Phone.listen (5) Print (' Server start ... ') before bind Conn,client_ Addr=phone.accept () while True: #通讯循环    client_data=conn.recv (1024x768)    # print (' has Rev ')    Conn.send (Client_ Data.upper ()) Conn.close () Phone.close ()

Client:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketphone=socket.socket (socket.AF_INET,socket. Sock_stream) Phone.connect ((' 127.0.0.1 ', 8080)) while True:    msg=input (' >>: '). Strip ()    if not msg: Continue    Phone.send (Msg.encode (' Utf-8 '))    # print (' ====>has send ')    SERVER_DATA=PHONE.RECV (1024)    # print (' ====>has recv ')    print (Server_data.decode (' Utf-8 ')) Phone.close ()

3. Link Loops

Service side:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketphone=socket.socket (socket.AF_INET,socket. SOCK_STREAM) phone.setsockopt (socket. Sol_socket,socket. so_reuseaddr,1) #就是它, Phone.bind ((' 127.0.0.1 ', 8080)) Phone.listen (5) Print (' Server start ... ') in front of BIND and True: #链接循环    conn,client_addr=phone.accept ()    print (conn,client_addr) while    True: #通讯循环        try:            client_data= CONN.RECV (1024x768)            if not client_data:break #针对linux系统            # print (' Have Rev ')            Conn.send (Client_data.upper ())        except Exception: #针对windwos            break    conn.close () phone.close ()

Client:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketphone=socket.socket (socket.AF_INET,socket. Sock_stream) Phone.connect ((' 127.0.0.1 ', 8080)) while True:    msg=input (' >>: '). Strip ()    if not msg: Continue    Phone.send (Msg.encode (' Utf-8 '))    # print (' ====>has send ')    SERVER_DATA=PHONE.RECV (1024)    # print (' ====>has recv ')    print (Server_data.decode (' Utf-8 ')) Phone.close ()

4. Solve the sticky bag phenomenon

Service side:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketimport structimport subprocessimport jsonphone= Socket.socket (Socket.af_inet,socket. SOCK_STREAM) phone.setsockopt (socket. Sol_socket,socket.    so_reuseaddr,1) #就是它, Phone.bind ((' 127.0.0.1 ', 8080)) Phone.listen (5) Print (' Server start ... ') in front of BIND and True: #链接循环             Conn,client_addr=phone.accept () print (CONN,CLIENT_ADDR) while True: #通讯循环 try:cmd=conn.recv (1024) If not cmd:break #执行命令, get the result res=subprocess. Popen (Cmd.decode (' Utf-8 '), Shell=true, stdout=subprocess. PIPE, Stderr=subprocess. PIPE) Stdout=res.stdout.read () stderr=res.stderr.read () #制作报头 header_dic={' tot Al_size ': Len (stdout) +len (stderr), ' MD5 ': None} header_json=json.dumps (Header_dic) header_bytes=header_ Json.encode (' Utf-8 ') #1 the length of the first header (fixed 4 bytes) conn.send (Struct.pack (' I ', Len (header_bytes))) #2 first send the header conn.send (header_bytes) #3 then send the real data Conn.send (stdout) conn.send (stderr) except Exception: #针对windwos break Conn.close () Pho Ne.close ()

Client:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketimport structimport jsonphone=socket.socket (Socket.AF _inet,socket. Sock_stream) Phone.connect ((' 127.0.0.1 ', 8080)) while True:    cmd=input (' >>: '). Strip ()    if not cmd: Continue    #发命令    phone.send (Cmd.encode (' Utf-8 '))    #先收报头的长度    struct_res=phone.recv (4)    Header_ Size=struct.unpack (' i ', struct_res) [0]    #再收报头    header_bytes=phone.recv (header_size)    Head_json=header_ Bytes.decode (' Utf-8 ')    head_dic=json.loads (Head_json)    total_size=head_dic[' total_size ']    # Re-order execution results    recv_size=0    data=b "while    recv_size < total_size:        RECV_DATA=PHONE.RECV (1024)        Recv_size+=len (recv_data)        data+=recv_data    #打印结果    print (Data.decode (' GBK ')) Phone.close ()

5. Implementing concurrency

Service side:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketserverclass mytcphandler (socketserver. Baserequesthandler):    def handle (self): while        True: #通信循环            data=self.request.recv (1024x768)            Self.request.send (Data.upper ()) If __name__ = = ' __main__ ':    #取代链接循环    server=socketserver. Threadingtcpserver ((' 127.0.0.1 ', 8080), Mytcphandler)    server.serve_forever ()

Client:

#!/usr/bin/env pyhon# encoding:utf-8# auth:yangleiimport socketphone=socket.socket (socket.AF_INET,socket. Sock_stream) Phone.connect ((' 127.0.0.1 ', 8080)) while True:    msg=input (' >>: '). Strip ()    if not msg: Continue    Phone.send (Msg.encode (' Utf-8 '))    server_data=phone.recv (1024x768)    print (Server_data.decode (' Utf-8 ')) Phone.close ()

Eighth: Python Basics _8 Object-oriented and network programming

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.