python基础补漏-09-反射
isinstance
class A:
pass
class B(A):
pass
b = B()
print isinatance(b,A)
issubclass 判断某一个类是不是另外一个类的派生类
#################################################################
自定义异常
class demoerror(Exception):
def __str__(self):
return 'this is error'
try:
raise demoerror()
except Exception ,e:
print e、
#################################################################
自定义一个带参数的异常
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
#################################################################
反射:根据参数的名字 动态的调用方法
【1】getattr ---> 获取某个容器的某个函数
---------index.py
import home
res = 'home'
func = getattr(home,res) # 获取 home模块里面的 home函数
res = func() # 执行并且获取返回值
print res
------------home.py
def home():
print 'home'
return 'ok'
结果:
home
ok
【2】 hasattr -->判断某个容器是不是有某个模块
--------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'
结果:
True False
------------------------------------------------------------
模拟web框架中的使用
-------------webdemo.py
from wsgiref.simple_server import make_server
def RunServer(environ,start_response):
start_response('200 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
其他应用
setattr:给某个容器设置一个方法
----index.py
import home
res = 'lala'
func = setattr(home,res,'hello world')
fures = getattr(home,res)
print fures
输出:
hello world
在内存中给home这个空间 设置设置一个方法 res
-----------------------------------
delattr:删除某个函数的方法
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
#################################################################
反射操作类的成员
__author__ = 'Administrator'
class Leo:
start_name = 'rico'
def __init__(self):
self.start_name = 'NEO'
def show(self):
print 'show me'
@staticmethod
def start_show():
print 'start_show'
@classmethod
def class_show(cls):
print 'class_show'
print Leo.__dict__.keys()
print hasattr(Leo,'show')
=======================================================
反射导入多层模块
--index.py
__author__ = 'Administrator'
import home
cls = getattr(home,'Leo')
print cls
s_name = getattr(cls,"start_name")
print s_name
--home.py
class Leo:
start_name = 'rico'
def __init__(self):
self.start_name = 'NEO'
def show(self):
print 'show me'
输出:
home.Leo
rico
----------------
--index.py
__author__ = 'Administrator'
import home
cls = getattr(home,'Leo')
obj =cls()
name = getattr(obj,"start_name")
print name
输出:
NEO
前者是类的静态字段 后者是调用类里的方法的静态字段
cls()代表实例化这个类
===========================================
动态导入模块
----home.py
__author__ = 'Administrator'
def index():
print 'index'
return 'return'
def home():
pass
---index.py
con,action = raw_input('url:').split('/')
module = __import__(con)
func= getattr(module,action)
ret = func()
print ret
输入输出:
url:home/index #输入
index --输出
return --输出
==========================================================