標籤:self html 反射 設定 定義 att 派生 容器 動態
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
#################################################################
python基礎補漏-09-反射