Isinstance
Class A:
Pass
Class B (A):
Pass
b = B ()
Print Isinatance (b,a)
Issubclass determine if a class is a derived class of another class
#################################################################
Custom exceptions
Class Demoerror (Exception):
def __str__ (self):
Return ' This is error '
Try
Raise Demoerror ()
Except Exception, E:
Print E,
#################################################################
To customize an exception with parameters
Class Demoerror (Exception):
def __init__ (self,msg):
self.msg = Msg
def __str__ (self):
If self.msg:
Return self.msg
Else
Return ' Sesesesesseseseese '
Try
Raise Demoerror (' Lalalalalalalalalala ')
Except Exception, E:
Print E
#################################################################
Reflection: Dynamic invocation Method According to the name of the parameter
"1" getattr---> Get a function of a container
---------index.py
Import Home
res = ' Home '
Func = GetAttr (home,res) # Gets the home function inside the home module
res = func () # executes and gets the return value
Print Res
------------home.py
Def home ():
print ' Home '
Return ' OK '
Results:
Home
Ok
"2" hasattr---determine if a container has a module
--------index.py
Import Home
res = ' Home '
RUS = ' Demo '
func1 = hasattr (home,res)
Func2 = hasattr (Home,rus)
Print Func1,func2
------------home.py
Def home ():
print ' Home '
Return ' OK '
Results:
True False
------------------------------------------------------------
Simulating use in a web framework
-------------webdemo.py
From Wsgiref.simple_server import Make_server
def runserver (environ,start_response):
Start_response (' K OK ', [(' Content-type ', ' text/html ')])
url = environ[' path_info ']
temp = url.split ('/') [1]
Import Home
Is_exist = hasattr (home.temp)
#home模块中检查有没有跟穿过来url名称一样的方法
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 "SERVER in 8001"
Httpd.serve_forever ()
----home.py
Xxxx
Xxxx
Xxxx
Other applications
SetAttr: Set a method for a container
----index.py
Import Home
res = ' Lala '
Func = SetAttr (home,res, ' Hello World ')
Fures = GetAttr (home,res)
Print Fures
Output:
Hello World
In memory give home this space setting set a method res
-----------------------------------
Delattr: How to delete a function
Import Home
res = ' Lala '
Func = SetAttr (home,res, ' Hello World ')
#res = GetAttr (home,res)
#print Res
func1 = delattr (home,res)
Res1 = hasattr (home,res)
Print Res1
#################################################################
Python Base trapping -09-reflection