Advanced Python Applications (iii) object-oriented programming step-by-step
Key points to learn in this chapter:
- Object-oriented Advanced Syntax section
- Static methods, class methods, property methods
- Special methods for classes
- Reflection
- Exception handling
- Socket Development Basics
first, the object-oriented Advanced Syntax sectionStatic methods
To use a static method in a class, precede the class member function with the @staticmethod tag to indicate that the following member function is a static function. The advantage of using static methods is that you do not need to define an instance to use this method. In addition, multiple instances share this static method.
Class method
A class method differs from a normal member function and a static function, and it seems that the semantics are not seen in the language in which it is defined:
A class method can be called by a class or its instance, whether you call this method with a class or a class instance, and the first parameter of the method always defines the method's class object.
Remember that the first parameter of a method is a class object and not an instance object.
By convention, the first parameter of a class method is named CLS. It is not necessary to define a class method at any time (the functionality that a class method can implement can be implemented by defining a common function, as long as the function accepts a class object as a parameter).
The implementation of both static and class methods in Python is dependent on the Python decorator. The object method has a self parameter, and the class method has a CLS parameter, and the static method does not require these additional parameters.
Class Testclassmethod (Object): method = ' method HoHo ' def __init__ (self): self.name = ' Leon ' def test1 (self): print ( ' test1 ') print (self) @classmethod def test2 (CLS): print (CLS) print (' Test2 print (testclassmethod.method) print ( '----------------') @staticmethod def test3 (): Print (Testclassmethod.method) print (' test3 ') if __name__ = = ' __main__ ': a = Testclassmethod () A.test1 () a.test2 () a.test3 () testclassmethod.test3 ()
Output:
Test1 as an instance method
Test2 is a class method, the first argument is the class itself
Test3 is a static method and can not receive parameters
Class methods and static methods can access static variables (class variables) of a class, but cannot access instance variables, Test2, test3 cannot access self.name, and test1 can
test1<__main__. Testclassmethod object at 0x0061bd30><class ' __main__. Testclassmethod ' >test2method HoHo----------------method Hohotest3method Hohotest3
Property method
The function of a property method is to turn a method into a static property by @property
Python's built-in @property
decorator is responsible for turning a method into a property invocation:
Class Student (object): @property def score (self): return Self._score @score. Setter def score ( Self, value): if not isinstance (value, int): raise ValueError (' score must is an integer! ') If value < 0 or value >: raise ValueError (' score must between 0 ~ 100! ') Self._score = value
@property
Implementation is more complex, we first examine how to use. To turn a getter method into a property, just add it, and @property
at this point, it @property
creates another adorner @score.setter
, which is responsible for turning a setter method into a property assignment, so we have a controllable property operation:
>>> s = Student () >>> S.score = OK, actual conversion to S.set_score >>> S.score # OK, actual conversion to S.get_score () 60>>> S.score = 9999Traceback (most recent call last): ... Valueerror:score must between 0 ~ 100!
Notice that this magical @property
, when we operate on instance properties, we know that this property is probably not directly exposed, but is implemented through getter and setter methods.
You can also define read-only properties, define getter methods only, and do not define setter methods as a read-only property:
Class Student (object): @property def Birth (self): return Self._birth @birth. Setter def birth ( Self, value): Self._birth = value @property def-age (self) : return 2016-self._birth
The above birth
is a read-write property, which age
is a readonly property because age
it can be calculated based on the birth
current time.
Special method for Class 1. __DOC__ represents the description of a class
Class Foo: "" " describes the classes information, which is used for viewing the Magic" " def func (self): pass Print foo.__doc__# Output: class description Information
2.
__module__ and __class__
__MODULE__ represents the object of the current operation in that module
__CLASS__ represents the class of the object that is currently being manipulated
Class C: def __init__ (self): self.name = ' Wupeiqi '
From LIB.AA Import cobj = C () print obj.__module__ # output LIB.AA, i.e.: Output module print obj.__class__ # output LIB.AA.C, i.e. output class
3. __init__ constructs a method that automatically triggers execution when an object is created through a class. 4.
__del__
destructor, which automatically triggers execution when the object is freed in memory.
Note: This method is generally not defined because Python is a high-level language, and programmers do not need to be concerned with allocating and releasing memory because this work is done by the Python interpreter, so the destructor calls are automatically triggered by the interpreter when it is garbage collected.
5. The __call__ object is appended with parentheses to trigger execution.
Note: The execution of the construction method is triggered by the creation object, that is: Object = class name (), and the execution of the __call__ method is triggered by parentheses after the object, i.e.: Object () or Class () ()
Class Foo: def __init__ (self): pass def __call__ (self, *args, **kwargs): print ' __call__ ' obj = Foo () # Execute __init__obj () # Execute __call__
6.__DICT__ View all members in a class or object
Class Province: country = ' China ' def __init__ (self, Name, count): self.name = name Self.count = count< C4/>def func (self, *args, **kwargs): print ' func ' # gets the member of the class, namely: Static field, method, print province.__dict__# output: {' Country ': ' China ', ' __module__ ': ' __main__ ', ' func ': <function func at 0x10be30f50>, ' __init__ ': <function __init__ at 0x10be30ed 8>, ' __doc__ ': None} obj1 = Province (' Hebei ', 10000) print obj1.__dict__# get the member of Object Obj1 # output: {' count ': 10000, ' name ': ' HeB Ei '} obj2 = Province (' Henan ', 3888) print obj2.__dict__# Gets the member of the object Obj1 # output: {' count ': 3888, ' name ': ' Henan '}
7.
__str__If the __str__ method is defined in a class, the return value of the method is output by default when the object is printed
Class Foo: def __str__ (self): return ' Alex li ' obj = Foo () print obj# output: Alex Li
8.
__getitem__, __setitem__, __delitem__
Used for index operations, such as dictionaries. Each of the above represents the acquisition, setting, and deletion of data
Class Foo (object): def __getitem__ (self, key): print (' __getitem__ ', key) def __setitem__ (self, key, value ): print (' __setitem__ ', key,value) def __delitem__ (self, key): print (' __delitem__ ', key) obj = Foo () result = obj[' K1 ' # automatically triggers execution __getitem__obj[' k2 ') = ' Alex ' # automatically triggers execution __setitem__del obj[' K1 ']
9. __new__ \ __metaclass__
Class Foo (object): def __init__ (self,name): self.name = name f = Foo ("Alex")
Reflection
The following 4 methods are used to map or modify the state, properties, and methods of a program when it is run
Class Foo (object): def __init__ (self): self.name = ' Wupeiqi ' def func: return ' func ' obj = Foo () # # # # # # # # # # # # # # # # # # # # # # # # # #hasattr (obj, ' name ') # # # # # # # # # # #getattr (obj, ' name ') getattr (obj, ' func ') # # # # # # # # Hasattr Set member # # # #setattr (obj, ' age ', setattr) (obj, ' show ', Lambda Num:num + 1) # # # # # # # # # # # # # # #delattr (obj, ' name ') delattr (obj , ' func ') Reflection code example
second, exception handling
Python Standard exception
Exception Name Description Baseexception base class for all exceptions Systemexit interpreter request exit Keyboardinterrupt user interrupt Execution (usually input ^c) Exception General error base class Stopiteration iterator no more values Generatorexit generator (generator) An exception occurred to notify the base class of all built-in standard exceptions that exited StandardError arithmeticerror all numeric calculation errors for base class Floatingpointerror floating-point calculation error overflowerror numeric operation exceeded maximum limit Zerodivisioner Ror except (or modulo) 0 (all data types) Assertionerror Assertion statement failed Attributeerror object does not have this property Eoferror no built-in input, reached EOF Flag EnvironmentError Operating system error base class IOError input/output operation failed OSError operating system error Windowserror system call failed Importerror Import module/ Object failed lookuperror Invalid data query base class Indexerror sequence does not have this index (index) in Keyerror mapping does not have this key Memoryerror memory overflow error (not fatal for Python interpreter) Nameerror non-declaration/initialization Object (no attribute) Unboundlocalerror access to uninitialized local variable referenceerror weak reference (Weak reference) An attempt was made to access a garbage-collected object RuntimeError general run-time error notimplementederror a method that has not yet been implemented Syntaxerrorpython Syntax error Indentationerror indentation error Taberrortab mixed with spaces Systemerror General interpreter system error TypeError an operation that is not valid for type ValueError passed in an invalid parameter Unicodeerrorunicode related error Unicodedecodeerrorunicode Error Unicodeencodeerrorunicode encoding when decoding error Unicodetranslateerrorunicode The base class for the error warning warning on conversion deprecationwarning warning about deprecated features futurewarning warning about constructing future semantics overflowwarningOld warning about auto-promotion to Long Integer (long) pendingdeprecationwarning runtimewarning suspicious runtime behavior for attributes that will be discarded (runtime behavior) Warning syntaxwarning suspicious syntax warning userwarning user code generated warning
Exception handling
You can use the Try/except statement to catch an exception.
The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.
If you do not want to end your program when an exception occurs, simply capture it in a try.
Grammar:
The following is a simple syntax for try....except...else :
try:< Statement > #运行别的代码except < name >:< statement > #如果在try部份引发了 ' name ' exception except < name >,< data >:< Statement > #如果引发了 ' name ' exception, get additional data else:< statement > #如果没有异常发生
Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.
- If an exception occurs when the statement after the try is executed, Python jumps back to the try and executes the first except clause that matches the exception, and the control flow passes through the entire try statement (unless a new exception is thrown when the exception is handled).
- If an exception occurs in the statement after the try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top of the program (This will end the program and print the default error message).
- If no exception occurs when the TRY clause executes, Python executes the statement after the Else statement (if there is else), and then the control flow passes through the entire try statement.
Instance
Here is a simple example that opens a file where the contents of the file are written and the exception does not occur:
#!/usr/bin/python#-*-coding:utf-8-*-try: fh = open ("Testfile", "W") Fh.write ("This is a test file for testing exceptions!") Except IOError: print "Error: Failed to find file or read file" else: print "content written to file succeeded" Fh.close ()
The above program output results:
$ python test.py content written to file successfully $ cat testfile # View written content This is a test file for testing exceptions!!
Instance
Here is a simple example that opens a file where the contents of the file are written, but the file does not have write permission, and an exception occurs:
#!/usr/bin/python#-*-coding:utf-8-*-try: fh = open ("Testfile", "W") Fh.write ("This is a test file for testing exceptions!") Except IOError: print "Error: Failed to find file or read file" else: print "content written to file succeeded" Fh.close ()
In order to test the convenience before executing the code, we can first remove the testfile file Write permission, the command is as follows:
Chmod-w testfile
Then execute the above code:
$ python test.py Error: Failed to find file or read file
Use except without any exception type
You can use except without any exception type, as in the following example:
Try: normal operation ... except: An exception occurred, execution of this code ... else: ".".??????????????????????? If there is no exception to execute this piece of code
The try-except statement above captures all occurrences of the exception. But this is not a good way to identify specific exception information through the program. Because it catches all the exceptions.
Using except with multiple exception types
You can also use the same except statement to handle multiple exception information, as follows:
Try: normal operation ... except (exception1[, exception2[,..., ....., .... ..... Exceptionn]]): The occurrence of one of the above multiple exceptions, the execution of this code ... else: If there is no exception to execute this block of code,
try-finally statements
The try-finally statement executes the final code regardless of whether an exception occurs.
try:< statements >finally:< statements > #退出try时总会执行raise
Instance
#!/usr/bin/python#-*-coding:utf-8-*-try: fh = open ("Testfile", "W") Fh.write ("This is a test file for testing exceptions!") Finally: print "Error: Failed to find file or read file"
If the open file does not have writable permissions, the output is as follows:
$ python test.py Error: Failed to find file or read file
The same example can be written in the following way:
#!/usr/bin/python#-*-coding:utf-8-*-try: fh = open ("Testfile", "W") try: fh.write ("This is a test file for testing exceptions!") finally: print "Close file" fh.close () except IOError: print "Error: Failed to find file or read file"
Executes the finally block code immediately when an exception is thrown in the try block.
After all the statements in the finally block are executed, the exception is triggered again, and the except block code is executed.
The contents of the parameter differ from the exception
Third, Socket Development FoundationWhat is a Socket?
A socket is also called a socket, and an application usually makes a request to the network through a "socket" or responds to a network request, making it possible to communicate between hosts or between processes on a computer.
Socket () function
In Python, we use the socket () function to create a socket with the following syntax:
Socket.socket ([family[, type[, Proto]])
Parameters
- Family: The socket family can make Af_unix or af_inet
- Type: The socket type can be divided into either a connection-oriented or a non-connected
SOCK_STREAM
SOCK_DGRAM
- Protocol: General does not fill the default is 0.
A simple server/client program.
Server Side
#!/usr/bin/env python#-*-coding:utf-8-*-import socketip_port = (' 127.0.0.1 ', 9999) 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 (' Don't answer, don't answer, don't answer ') conn.close ()
Client Side
#!/usr/bin/env python#-*-coding:utf-8-*-import socketip_port = (' 127.0.0.1 ', 9999) SK = Socket.socket () sk.connect (ip_ Port) Sk.sendall (' request to occupy the earth ') server_reply = Sk.recv (1024x768) print server_replysk.close ()
On-the-Go Python "seventh chapter": Advanced Application of Python (iv) object-oriented programming