finish This section, the basic part of Python will be finished, looking forward to a new stage of learning, but also to their insistence is victory.
Yi, Isinstance (obj,cls)
To check if obj is a CLS object
1. Start with the learned variables first
A = 12b = "BB" Print isinstance (a,int) #结果是Trueprint isinstance (a,str) #结果是Falseprint isinstance (b,str) #结果是Trueprint Isin Stance (B,int) #结果是False
In fact, that is to say: The variable, a, is the object, whether it is a class belonging to Int,str, belongs to return True, does not belong to return false
2. Relationships between objects and classes in a class
Class Foo:def __init__ (self): Pass def func (self): Passobj = Foo () print isinstance (Obj,foo) #结果是True
3. Relationship of objects and base classes
Class Foo:def __init__ (self): Pass def func (self): Passclass Bar (Foo): Passobj = Bar () print isinst Ance (Obj,bar) #结果为Trueprint isinstance (Obj,foo) #结果是True
Summarize:
Isinstance is to determine whether an object belongs to a class
Is the relationship between the object and the class
Relationship of objects and base classes
Second, Issubclass (Sub,super)
To check if a sub is a derived class of super
Class Foo:def __init__ (self): Pass def func (self): Passclass Bar (Foo): Passprint Issubclass (BAR,FO O) #结果为True
Third, exception handling
1, the cause of the production
In order to increase the friendliness of the user interaction during the programming process, the error message is not displayed to the user when the program is in error, that is, it will not appear in the large yellow pages when we usually browse the page, but instead display an error prompt interface.
2. How to handle exceptions in Python
Try:passexcept Exception E:pass
The correct logic code in try
Error in code logic block in except
For example:
input = raw_input ("Input:") data = Int (input)
Try:input = Raw_input ("Input:") data = Int (input) except Exception,e:print "Please enter a number"
In a piece of code, add me to enter a number, the program will not error, and when I enter the letter, the program will error.
In addition to the code of try and except block, when the number is entered, the program will still not error, and input non-number will print the prompt message, let you enter the number.
By comparing the above, it can be seen that the code with exception handling is much more friendly to the user interaction than the code without exception handling.
3. Types of anomalies
1), the specified exception
DiC = {' K1 ': ' v1 ', ' K2 ': ' v2 '}try:dic[' K3 ']except keyerror,e:print E
DIC = ["Tom", ' BB ']try:dic[10] except Indexerror, E:print E#list index out of range
S1 = ' Hello ' try:int (S1) except ValueError, E:print e#invalid literal for int. () with base: ' Hello '
The above code exceptions are specified for specific error handling, such as key,index,value, but there are some problems with this processing, such as:
#假如你写成下面的异常处理, the program failed to catch the exception, the program directly error S1 = ' Hello ' try:int (S1) except Indexerror,e:print E
In response to this problem, we generally write the following exception handling sequence when we handle exceptions
S1 = ' Hello ' try:int (S1) except Indexerror,e:print eexcept keyerror,e:print eexcept valueerror,e:print eexce PT Exception,e:print E
That is to say, write a special first, finally write the final exception,exception is also called the universal Anomaly, can catch arbitrary anomalies.
But in turn, if you have a universal exception that captures arbitrary exceptions, what do you need to do with special exceptions?
The answer is this: exceptions for special handling or reminders need to be defined first and finally defined exception to ensure that the program is working properly.
Summarize the special exceptions
Arithmeticerror
Assertionerror
Attributeerror
Baseexception
Buffererror
Byteswarning
Deprecationwarning
EnvironmentError
Eoferror
Exception
Floatingpointerror
Futurewarning
Generatorexit
Importerror
Importwarning
Indentationerror
Indexerror
IOError
Keyboardinterrupt
Keyerror
Lookuperror
Memoryerror
Nameerror
Notimplementederror
OSError
Overflowerror
Pendingdeprecationwarning
Referenceerror
RuntimeError
Runtimewarning
StandardError
Stopiteration
SyntaxError
Syntaxwarning
Systemerror
Systemexit
Taberror
TypeError
Unboundlocalerror
Unicodedecodeerror
Unicodeencodeerror
Unicodeerror
Unicodetranslateerror
Unicodewarning
Userwarning
ValueError
Warning
Zerodivisionerror
4, the large structure of the anomaly
Try: #主代码块, logic code passexcept indexerror,e: #异常处理 passexcept exception,e:passelse: #逻辑块中未出现异常, the PA is executed after the main code block has finished executing Ssfinally: #永远执行, execute pass after logic code executes
5. Active Trigger exception
#导入另外一个模块 and then calls the method in the Import Helper #helper里有方法f1 (), which returns a value if __name__ = = "__main__": try:n = "1" n = Int (n) Ind EXERROR ret = HELPER.F1 () If Ret:print "Success" Else: #出现错误 raise Exception ("error occurred") Exce PT Exception,e:print "Error occurred" Print E
If the returned value is False, the error is actively triggered, that is, raise Exception ("error occurred")
Summary:
1, the above about the handling of the exception, there will be an E: What is its role?
Answer: E is an object that encapsulates indexerror and so on into E, equivalent to a field in a class encapsulated in an object.
2. What is the relationship between exception and these special treatment Indexerror?
Answer: Exception is their base class.
3, why the following exception will print such a hint?
Try
int ("AA")
Except Exception,e:
Print E
#异常结果为: Invalid literal for int. () with base: ' AA '
Give the answer first: it is generated by the __str__ method in the class.
For example:
Class a:passobj = A () print obj# result is <__main__. A instance at 0x023ef7b0>
So we can see that the result of print E in the exception is a string, and the print object in the class is a memory address, so what can be done with print e?
Class A:def __str__ (self): return "AA" obj = A () print obj# result of AA
By adding the __str__ method to the class and printing the object again, a string is printed, which is the same as printing the invalid literal for int in the exception () with base: The ' AA ' principle.
The essence is: In the exception, E is the object, and exception is the class, that is, the object E calls the __str__ method in the class exception to get the result.
6. Custom Exceptions
#类crazyException继承了类Exceptionclass crazyexception (Exception): #将msg封装到对象e中 def __init__ (self, msg= None): #初始值msg为Non E self.message = msg def __str__ (self): if Self.message:return self.message else: Return ' crazyexception ' try:raise crazyexception (' my exception ') except Exception,e:print E
7. Assert: Assert
function in the program debugging, determine whether the program is correct, for debug
Assert condition
If the condition is true, will not error, otherwise, the program error
For example:
Assert 1==1
Assert 1==2
Iv. Reflection
1, the reflection function in Python is provided by four kinds of built-in functions, hasattr,setattr,getattr,delattr these four built-in functions are used for internal execution of objects: check if a member is included, set a member, get a member, delete a member
Class Foo (object): Def __init__ (self): Self.name = ' Tom ' def func: Return ' func ' obj = Foo () # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #getattr (obj, ' hasattr ') # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # GetAttr # # # # #setattr (obj, ' age ', setattr) (obj, ' show ', Lambda Num:num + 1) # # # # # # # # # # # # # # # #delattr (obj, ' name ') delattr (obj, ' Fu NC ')
2, below through the example step by step discussion reflection:
1), we simulate the web as an example
home.py
def index (): Return ' Home.index ' Def Dev (): Return ' Home.dev '
Import Homeurl = raw_input ("URL:") if url = = "Home/dev": ret = Home.dev () print retelif URL = = "Home/index": ret = Home.index () print Retelse:print "404"
This means that we enter the corresponding URL, and then make a decision to find the URL that matches the criteria, return value
Below we use reflection to operate
url = raw_input ("URL:") #url = Home/devcontroller,action = Url.split ('/') import home#action = string # Go to a container or module, find the function, the string is the function name, If there is, then gets the function func = GetAttr (home,action) #在home中找action, if there is a return reply number name RET = func () #函数名加括号, which represents the execution function, returns the result retprint ret
So in the above code there is no need to judge, just go to the home module to find the matching URL, which for a large number of URLs, with reflection is simple.
2) Compare the results from four built-in functions
Import Homeprint dir (home) #结果为 [' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' dev ', ' index ']print Hasattr (home, ' Dev ') #结果为Trueprint getattr (home, ' Dev ') #结果 <function Dev at 0x026072f0>setattr (home, ' show ', Lambda x:x + 1) print dir (home) #结果为 [' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ', ' dev ', ' index ', ' #s How '] #多了showdelattr (home, ' show ') print dir (home) #结果为 [' __builtins__ ', ' __doc__ ', ' __file__ ', ' __name__ ', ' __package__ ' Dev ', ' index '] #将show删除了
3) test on the Web (Practice reflection)
#!/usr/bin/env python#coding:utf-8from wsgiref.simple_server import make_serverdef Runserver (Environ, start_response): start_response (' 200 OK ', [(' Content-type ', ' text/html ')] url = environ[' PATH_INFO '] temp = url.split ('/') [1] import home #去home模块中检查, whether it contains the specified function is_exist = hasattr (home, temp) #如果存在指定的函数 if is_exist: #获取函数 func = getattr (home, temp) #执行函数并获取返回值 ret = func ( ) #将函数返回值响应给请求者 Return ret else: return ' 404 not found ' if __ name__ == ' __main__ ': httpd = make_server (', 8001, Runserver) print "serving http on port 8001 ..." httpd.serve_forever ()
3, Reflection action classes, and members in objects
class foo: static_name = ' Tom ' def __init__ (self): self.name = "Eric" def show (self): pass @staticmethod def static_method (): pass @classmethod def Class_show (CLS): pass# See what methods are in the Class Print foo.__dict__.keys () # [' __module__ ', ' Static_method ', ' show ', ' static_name ', ' class_show ', ' __doc__ ', ' __init__ ']print hasattr (Foo, ' class_show ') #看类中是否有class_show方法obj = foo () #看对象中有什么 with the result {' Name ': ' Eric '}print obj.__dict__print hasattr (obj, ' name ') #结果为Trueprint hasattr (obj, ' Show ') #结果为True
Why the object has only name, and hasattr (obj, ' Show ') is displayed as true, because there is a class object pointer in the object, the object is first found in its own memory, if not found in the class, so it will be found, the return result is true
4, the above operation is in their own module of the internal execution, the next look at the other modules to perform the effect
Import homecls = GetAttr (home, ' Foo ') print CLS #home. Foo gets the class obj = CLS () #cls是类, and the class parentheses are instantiated, that is, creating the object, executing the __init__ method name = GetAttr (obj, ' name ') #在对象中找nameprint name
Summarize reflections: Find the elements of an object in a container
5. Dynamic Import Module
Try:controller,action = raw_input ("URL:"). Split ("/") module = __import__ (Controller) func = GetAttr (module,actio N) ret = func () print retexcept exception,e:print "Please enter URL correctly"
Five, single-case mode
Singleton is an individual instance
The singleton mode exists to ensure that there is only one instance in memory to avoid wasted memory
A comparison of two examples to illustrate a single case pattern
1, do not use a single case mode
Class Sqlhelper:def __init__ (self,name): Self.name = "Tom" self.name = Name def show (self): PA Ssobj1 = SqlHelper (1) Print ID (obj1) #37025832obj2 = SqlHelper (1) Print ID (obj2) #37195368
This creates an instance of SqlHelper (1), but generates a different ID that consumes a lot of memory.
2. Adopt Single Instance Mode
class sqlhelper: __static_instance = none def __init__ (self): self.hostname = ' 0.0.0.0 ' self.port = 3306 self.user = ' root ' @classmethod def instance (CLS): #cls = SqlHelper if cls.__static_instance: return cls.__static_instance else: cls.__static_instance = sqlhelper () return Cls.__static_instanceobj1 =&nBsp Sqlhelper.instance () Print id (obj1) #38833768obj2 = sqlhelper.instance () print id (OBJ2) #38833768
1. create static field __static_instance = None Save An instance of memory that is always present
2, call the class method @classmethod, return that object
3. Get an instance of persistent memory through a class object
This is the point of creating a singleton pattern .....
Reference Source:
http://www.cnblogs.com/wupeiqi/
And the old boy Python development video
This article is from the "Crazyforever" blog, make sure to keep this source http://crazyforever.blog.51cto.com/7362974/1737341
Python learns------------anomalies and reflections