day7-Live content (hanyyyy teacher)

Source: Internet
Author: User

    
*******************************
Class Animal (object):
def __init__ (self):
Self.is_handsome=true

Def eat (self):
If Self.is_handsome:
Print "Eat ..."
Else
Print "No Handsome"

Class Dog (animal):
def __init__ (self):
#animal. __init__ (self)
Super (Dog,self). __init__ ()
Self.hair= "BLACK"

def bite (self):
Print "Bite me!"

D=dog ()
D.bite ()
D.eat ()

******************************************



I have a dictionary that gets from somewhere, like an HTTP request, and I'm going to follow this.
Dictionary to build an object.

Class Person:
def __init__ (self,_obj):
Self.name = _obj[' name ']
Self.age = _obj[' age ']
Self.energy = _obj[' energy ')
Self.gender = _obj[' gender ']
Self.email = _obj[' email ']
Self.phone = _obj[' phone ']
Self.country = _obj[' Country ']

Class Person:
def __init__ (self,_obj):
Self.__dict__.update (_obj)


In Python, everything is an object, and these objects are instantiated from a type, so to speak,
These objects have properties and methods, and properties can store some values. And intuitively, anything that can store
Things, we can say that it has a space (only there is room to store things), and in
In programming, we typically use the term namespace or namespace (namespace) to address it. Such
We can conclude that each object has a namespace. In Python, we use the __dict__ of the object
property to hold something in the namespace of the object, __dict__ is a dictionary ("key-value" pair, general "key"
is the property name or method name, which is the value of the property or the real method entity object that the method name points to.

#__dict__: Instance Properties
Class Animal:
Price = 10
__a = 22
def __init__ (self):
Self.__color = "Red"
Self.__price = 11

Class Dog (Animal):
__b = 10
C = 33

if __name__ = = "__main__":
Dog=dog ()
Print (dog.__dict__)

*******************************************
In Python, overloaded __getattr__, __setattr__, __delattr__, and __getattribute__
Method can be used to manage property access in a custom class. Where the __getattr__ method will intercept the
There is an undefined property fetch (that is, when the property to be accessed is already defined, the method is not called, as
The definition is undefined and is determined by whether Python can find the property); the __getattribute__ method will
Intercept all attributes (whether or not the property has been defined, as long as it gets its value, the method
Because of this situation, when __getattr__ and __getattribute__ are overloaded in a class
method, then __getattr__ is never called, and the __getattribute__ method exists only in
Python2.6 in all classes of the new class and Python3; the __setattr__ method will intercept all attributes assigned to the
The __delattr__ method will intercept all property deletions. Description: In Python, a class or class is actually
The properties in the example are dynamic (because Python is dynamic), that is, you can go to a class or class
example, add or remove an attribute.


1.1 Overloaded __setattr__ Method:
You cannot use the "Self.name = value" format when overloading the __setattr__ method, otherwise it will cause
Recursive calls into a dead loop. The correct one should be:

def __setattr__ (self, Name, value):
# do-something
Object.__setattr__ (self, name, value)
# do-something

Note: One of the words "object.__setattr__ (self, Name, value)" can be replaced by
"Self.__dict__[name] = value";

1.2 Overloaded __delattr__ Method:
You cannot use the Del self.name format when overloading the __delattr__ method, otherwise it will cause recursion
Call and fall into a dead loop. The correct one should be:

def __delattr__ (self, name):
# do-something
Object.__delattr__ (self, name)
# do-something

Note: One of the words "object.__delattr__ (self, name)" can be replaced by
"Del Self.__dict__[name]";

1.3 Overloaded __getattribute__ Method:

def __getattribute__ (self, name):
# do-something
Return object.__getattribute__ (self, name)
# do-something
"Return object.__getattribute__ (self, name) cannot be put in the __getattribute__ method
"Return Self.__dict__[name]" to avoid loops because it
(that is, self.__dict__) also triggers a property fetch, which in turn results in recursive invocation.

1.4 Overloaded __getattr__ Method:
Because the __getattr__ method is blocking undefined properties, it has no other three operator methods that
More restrictive, so you can write it like normal code. Its role is that when a piece of code
(the user writes, possibly intentionally, or unintentionally) when a property is not defined in a class or class instance.
How the program responds, and this response is in the __getattr__ method, which you decide.

************************************************************


Class computer (object):
def __init__ (self):
Self.brand= ""
Self.color= ""

def set_pro (Self,pro):
Self.brand,self.color=pro
def get_pro (self):
Return Self.brand,self.color

C=computer ()
Print C.get_pro ()
Print C.set_pro (("Gaier", "Red"))
Print C.get_pro ()

If we have a lot of attributes, this kind of writing is inappropriate, we can solve the problem by intercepting the property, we will
Some get, assignment operations are written in an intercept attribute function

Class Computer2 (object):
def __init__ (self):
self.brand= "1"
Self.color= ""
def __setattr__ (self, Key, value):
If key== "Pro":
Self.brand,self.color=value
Else
Self.__dict__[key]=value

def __getattr__ (self, item):
If item== "Pro":
Return Self.brand,self.color
Else
Raise Attributeerror
#print "Errors ..."

C2=computer2 ()
# c2.pro= ("sanxing", "Blue")
#
# Print C2.pro
# c2.a=4
# Print c2.a
# Print C2.ACD
#print C2.brand


C2.money=12
Print C2.money
Print C2.ABC
Print c2.__dict__

*******************************************************
2.7 Coding issues:



Python has a string of str object and Unicode object two, which can hold bytes of characters
Code, but they are different types, which is important and why there are encode and decode.

The significance of encode and decode in Pyhton can be expressed as

Encode
Unicode-------------------------> str (gb2312 or Utf-8)
Unicode <--------------------------str (gb2312 or Utf-8)
Decode
Several common methods:
Str_string.decode (' codec ') is to convert str_string to unicode_string, codec is the encoding of the source str_string
Unicode_string.encode (' codec ') is the encoding method of converting unicode_string to Str_string,codec, which is the target str_string
Str_string.decode (' From_codec '). Encode (' To_codec ') enables conversion between str_string of different encodings
Like what:
>>> t= ' Great Wall '
>>> T
' \xb3\xa4\xb3\xc7 '
>>> t.decode (' gb2312 '). Encode (' Utf-8 ')
' \xe9\x95\xbf\xe5\x9f\x8e '
Str_string.encode (' codec ') is the first call to the system's default codec to convert Str_string to
Unicode_string, then use the Encode parameter codec to convert to the final str_string. Equivalent
Str_string.decode (' Sys_codec '). Encode (' codec ').

*********************************************************
Socket (family,type[,protocal]) using the given address family, socket type, protocol number
(the default is 0) to create a socket.

S=socket.socket (Socket.af_inet,socket. SOCK_STREAM)
S=socket.socket (Socket.af_inet,socket. SOCK_DGRAM)

Service-Side socket function
S.bind: Binds a socket to an address, under Af_inet, in the form of a tuple (host,port)
Represents an address.
S.listen: Start listening for TCP incoming connections. The backlog specifies that before the connection is denied, the operating system
The maximum number of connections that can be suspended. This value is at least 1, and most applications are set to 5.

S.accept (): Accepts a TCP connection and returns (Conn,address), where Conn is a new socket object that can be
To receive and send data. Address is the location of the connection client.

Client socket function
S.connect (address): the socket connected to address. The format of the general address is a tuple
(Hostname,port), returns a socket.error error if there is an error in the connection.

S.RECV (Bufsize[,flag]): Accepts data for TCP sockets. The data is returned in string form,
BUFSIZE Specifies the maximum amount of data to receive. Flag provides additional information about the message, which can usually be ignored.
S.send (String[,flag]): Sends TCP data. Sends data from a string to a connected socket.
The return value is the number of bytes to send, which may be less than the byte size of the string.
S.sendall (String[,flag]): Complete sending of TCP data. To send data from a string to a connected socket
But will attempt to send all data before returning. Successful return none, Failure throws an exception.

S.close ()
Close the socket.
S.getpeername ()
Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
S.getsockname ()
Returns the socket's own address. Typically a tuple (ipaddr,port)
*********************************************************
EG1:
#!/usr/bin/env python
#-*-Coding:utf-8-*-

Import socket

Ip_port = (' 127.0.0.1 ', 9997)

SK = Socket.socket ()
Sk.bind (Ip_port)
Sk.listen (5)

While True:
print ' Server waiting ... '
CONN,ADDR = Sk.accept ()

Client_data = CONN.RECV (1024)
Print Client_data
Conn.sendall (' Fuck off! ')

Conn.close ()
----------------
#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import socket
Ip_port = (' 127.0.0.1 ', 9997)

SK = Socket.socket ()
Sk.connect (Ip_port)

Sk.sendall (' I Like you ')

server_reply = SK.RECV (1024)
Print server_reply

Print Sk.getpeername ()
Print "* * * *"
Print Sk.getsockname ()

Sk.close ()

***********************************************
EG2:
#!/usr/bin/env python
#coding: Utf-8
Import socket

def handle_request (client):
BUF = CLIENT.RECV (1024)
Client.send ("http/1.1 201 okkkkkk\r\n\r\n")
Client.send ("Hello, World")

def main ():
Sock = Socket.socket (socket.af_inet, socket. SOCK_STREAM)
Sock.bind ((' localhost ', 8082))
Sock.listen (5)

While True:
Connection, address = sock.accept ()
Handle_request (Connection)
Connection.close ()

if __name__ = = ' __main__ ':
Main ()

***********************************************
Eg3 (Talking):


#!/usr/bin/env python
#-*-Coding:utf-8-*-

Import socket


Ip_port = (' 127.0.0.1 ', 8884)
SK = Socket.socket ()
Sk.connect (Ip_port)
Print "Client startup:"
While True:
INP = raw_input (' >>> ')
Sk.sendall (INP)
SERVER_RESPONSE=SK.RECV (1024)
Print Server_response
If InP = = ' exit ':
Break
Sk.close ()
-----------------------
#!/usr/bin/env python
#-*-Coding:utf-8-*-


Import socket

Ip_port = (' 127.0.0.1 ', 8884)
SK = Socket.socket ()
Sk.bind (Ip_port)
Sk.listen (5)
Print "Server start ..."
While True:
Conn,address = Sk.accept ()
While True:
Try
CLIENT_DATA=CONN.RECV (1024)
Except Exception:
Break
Print Client_data
Print "Waiting ..."
#server_response =raw_input (">>>")
#conn. Sendall (Server_response)
Conn.sendall (Client_data)

Conn.close ()

Attention:
When we disconnect the first client, at this point the server side CLIENT_DATA=CONN.RECV (1024)
This will receive an empty string, resulting in a dead loop, which the Windows system treats as
A mistake, Unix/linux will not! So under Linux, you just have to judge if the Client_data is empty.
can be solved!

This problem is not related to 3.0/2.0.


*****************************************************
To solve the concurrency problem, we use the Socketserver module


#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Socketserver

Class MyServer (Socketserver.baserequesthandler):

def handle (self):
Print "Server start ..."
While True:
conn = Self.request
Print Self.client_address
While True:
Try
CLIENT_DATA=CONN.RECV (1024)
Except Exception:
Break
Print Client_data
Print "Waiting ..."
#server_response =raw_input (">>>")
#conn. Sendall (Server_response)
Conn.sendall (Client_data)

Conn.close ()
# Print Self.request,self.client_address,self.server


if __name__ = = ' __main__ ':
Server = Socketserver.threadingtcpserver ((' 127.0.0.1 ', 8090), MyServer)
Server.serve_forever ()
----------------------------------------------------



#!/usr/bin/env python
#-*-Coding:utf-8-*-

Import socket


Ip_port = (' 127.0.0.1 ', 8090)
SK = Socket.socket ()
Sk.connect (Ip_port)
Print "Client startup:"
While True:
INP = raw_input (' >>> ')
Sk.sendall (INP)
SERVER_RESPONSE=SK.RECV (1024)
Print Server_response
If InP = = ' exit ':
Break
Sk.close ()

*****************************************************
Ssh:

#!/usr/bin/env python
#-*-Coding:utf-8-*-
Import Socketserver
Import subprocess

Class MyServer (Socketserver.baserequesthandler):

def handle (self):
Print "Got connection from", self.client_address
While True:

Conn=self.request
DATA=CONN.RECV (1024)
Print "Recv cmd:%s"%data
Cmd_call=subprocess. Popen (data,shell=true,stdout=subprocess. PIPE)

Cmd_result=cmd_call.stdout.read ()
If Len (cmd_result) ==0:
Cmd_result=b "No output!"
Conn.send (str (len (cmd_result)))
#conn. recv (1024)
Conn.sendall (Cmd_result) # More than 1024 of the parts are put into the buffer, not blocked here

if __name__ = = ' __main__ ':
Server = Socketserver.threadingtcpserver ((' 127.0.0.1 ', 8091), MyServer)
Server.serve_forever ()


#dir ARP CD ipconfig

-------------------------------
#!/usr/bin/env python
#-*-Coding:utf-8-*-

Import socket

Ip_port = (' 127.0.0.1 ', 8091)
SK = Socket.socket ()
Sk.connect (Ip_port)
Print "Client startup:"
While True:
INP = raw_input (' >>> ')
If Len (INP) ==0:
Continue
If inp== "Q":
Break
Sk.sendall (INP)
RES_SIZE=SK.RECV (1024)
#sk. Send ("OK")
Print "Res_size", res_size
Total_size=int (Res_size)
Received_size=0
While True:

SERVER_RESPONSE=SK.RECV (1024)
Received_size+=len (Server_response)
If total_size==received_size:

Print Server_response
Break

Print Server_response


Sk.close ()

***********************************************************



day7-Live content (hanyyyy teacher)

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.