I. Extension methods for classes 1. Static methods
Syntax: @staticmethod, a static method cannot access a public property and cannot access a class. Can be called directly after instantiation, and in the method can be invoked by self. Invokes an instance variable or class variable.
1 classEat (object):2 def __init__(self,name):3Self.name =name4@staticmethod#static methods cannot access shared properties, cannot access instances5 defEat (Name,food):6 Print("%s is eating. %s"%(Name,food))7P.eat ("Alex"," Food")2. Class methods
Syntax: @classmethod, you can access only the public properties of a class and cannot access instance properties.
1 classDog (object):2Name ="I am a class variable"3 def __init__(self,name):4Self.name =name5 6 @classmethod7 defEat (self):8 Print("%s is eating"%self.name)9 Ten One AD = Dog ("Chenronghua") - d.eat () - the - #Execution Results - -I am a class variable isEating3. Attribute methods
Syntax: @property turn a method into a static property
1 classDog (object):2 3 def __init__(self,name):4Self.name =name5 6 @property7 defEat (self):8 Print("%s is eating"%self.name)9 Ten OneD = Dog ("Chenronghua") AD.eat
The flight query code of the property method
1 classFlight (object):2 def __init__(self,name):3Self.flight_name =name4 5 6 defChecking_status (self):7 Print("checking flight%s status"%self.flight_name)8 return19 Ten One @property A defFlight_status (self): -Status =self.checking_status () - ifStatus = =0: the Print("flight got canceled ...") - elifStatus = = 1 : - Print("flight is arrived ...") - elifStatus = = 2: + Print("flight has departured already ...") - Else: + Print("cannot confirm the flight status...,please check later") A at@flight_status. Setter#Modify - defFlight_status (self,status): -Status_dic = { -:"canceled", -:"arrived", -:"departured" in } - Print("\033[31;1mhas changed the flight status to \033[0m", Status_dic.get (status)) to +@flight_status. deleter#Delete - defFlight_status (self): the Print("status got removed ...") * $f = Flight ("CA980")Panax Notoginseng F.flight_status -F.flight_status = 2#Trigger @flight_status.setter the delF.flight_status#Trigger @flight_status.deleter4. Abstract class
1 classAlert (object):2 defSend (self):3 RaiseNotimplementederror4 classMailalert (Alert):5 defSend (self,msg):6 Print("---sending.", msg)7 classSmsalert (Alert):8 Pass9m =Mailalert ()TenM.send ("DF")Two. Special member methods for classes
1.__DOC__ represents the description of a class
2.__MODULE__ indicates which module the object of the current operation is in
3.__CLASS__ represents the class of the object that is currently being manipulated
class C: def __init__ (self): ' Wupeiqi ' from Import = C ()print obj.__module__ # output LIB.AA, i.e.: Output module print obj.__class__ # output lib.aa.c, i.e.: Output class
4.__init__ constructs a method that automatically triggers execution when an object is created from a class.
The 5.__del__ destructor automatically triggers execution when the object is freed in memory. This method generally does not need to be defined, Python is a high-level language, the programmer does not care about the allocation and release of memory, this work is given to the Python interpreter to execute, so the destructor call is an interpreter in the garbage collection automatically triggered execution.
The 6.__call__ object is appended with parentheses to trigger execution.
7.__dict__ View all members of a class or object
Three. Reflection
Maps or modifies the state, properties, methods of a program run through a string.
The reflection functionality in Python is provided by the following four built-in functions: Hasattr, GetAttr, SetAttr, delattr, and four functions for internal execution of objects: Check for a member, get a member, set a member, delete a member.
To be perfected ....
Four. Exception handling
In the programming process in order to increase the friendliness of the program in the event of a bug will not be displayed to the user error message, but the reality of a hint of the page, popular is not to let users see the big Yellow Pages!!!
Common types:
1 Attributeerror attempts to access a tree that does not have an object, such as foo.x, but Foo has no attribute x2IOError input/Output Exception: Basically, the file cannot be opened3 Importerror cannot introduce modules or packages; it is basically a path problem or a name error4 indentationerror syntax error (subclass); Code not aligned correctly5The indexerror index exceeds the sequence boundary, for example, when X has only three elements, but tries to access the X[5]6 Keyerror attempts to access keys that do not exist in the dictionary7Keyboardinterrupt Ctrl +C is pressed8 Nameerror using a variable that has not been assigned to an object9 syntaxerror python code is illegal, code can not compile (personally think this is a syntax error, write wrong)Ten TypeError Incoming object types are not compliant with the requirements One Unboundlocalerror attempts to access a local variable that has not yet been set, basically because there is another global variable with the same name. A cause you think you're accessing it -ValueError Pass in a value that is not expected by the caller, even if the value is of the correct type
Common Types
1 Try:2int'Add')3Li = [11,22]4li[100]5 exceptIndexerror as E:#comply with the case of the execution6 Print("1", E)7 exceptValueError as E:#comply with the case of the execution8 Print("2", E)9 exceptException as E:#can be matched to, the above is not satisfied with the case, matching the item. Ten Print("3", E) One Else: A Print("Else") - finally: - Print("finally")#I 'm sure we'll do it eventuallyFive. Socket programming
The socket is essentially a network between 2 computers, set up a channel, two computers through this channel to achieve the transmission of data.
Socket families address cluster: socket.af_inet #IPV4
Socket. Sock_stream #for TCP
Socket. Sock_dgram #for UDP
Socket. Sock_ram #原始套接字
Socket method:
socket.
socket(
family=af_inet,
type=sock_stream,
proto=0,
fileno=none)
Sk.bind (address) binds sockets to addresses
Sk.listen (backlog) #开始监听传入连接. The backlog specifies the maximum number of connections that can be suspended before a connection is rejected.
Sk.setblocking (BOOL)
Whether blocking (default true), if set to false, then the accept and recv when there is no data, the error.
Sk.accept ()
Accepts the connection and returns (Conn,address), where Conn is a new socket object that can be used to receive and send data. Address is the location of the connection client.
Incoming TCP Client connection (blocked) waiting for connection
Sk.connect (Address)
The socket that is connected to the address. Generally, address is in the form of a tuple (Hostname,port) and returns a socket.error error if there is an error in the connection.
SK.CONNECT_EX (Address)
Ditto, but there will be a return value, the connection succeeds when the return 0, the connection fails when the return encoding, for example: 10061
Sk.close ()
Close socket
SK.RECV (Bufsize[,flag])
Accepts the data for the socket. The data is returned as a string, and bufsize specifies the maximum quantity that can be received. Flag provides additional information about the message, which can usually be ignored.
Sk.recvfrom (Bufsize[.flag])
Similar to recv (), but the return value is (data,address). Where data is the string that contains the received information, address is the socket addressing that sent the data.
Sk.send (String[,flag])
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. That is, the specified content may not be sent all.
Sk.sendall (String[,flag])
Sends data from a string to a connected socket, but attempts to send all data before returning. Successful return none, Failure throws an exception.
Internally, the send is called recursively, sending all the content.
Sk.sendto (string[,flag],address)
Sends the data to the socket, address is a tuple in the form of (Ipaddr,port), specifying the remote address. The return value is the number of bytes sent. This function is mainly used for UDP protocol.
Sk.settimeout (Timeout)
Sets the timeout period for the socket operation, and timeout is a floating-point number in seconds. A value of None indicates no over-time. In general, hyper-times should be set when a socket is just created, as they may be used for connected operations (such as client connections waiting up to 5s)
Sk.getpeername ()
Returns the remote address of the connection socket. The return value is typically a tuple (ipaddr,port).
Sk.getsockname ()
Returns the socket's own address. Typically a tuple (ipaddr,port)
Sk.fileno ()
File descriptor for sockets
Final code, to be perfected ...
Python basic knowledge learning _day8