python基礎補漏-09-反射

來源:互聯網
上載者:User

標籤: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-反射

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.