python學習反射
執行個體1
腳本内容如下:
#coding: utf8
class myClass(object):
def fax(self):
print 'faxing....'
def copy(self):
print 'copying...'
def printing():
print 'printing....'
m = myClass()
if hasattr(m,'fax'): #判斷myClass類中是否有fax方法
func = getattr(m,'fax') #傳回記憶體對象
func() #調用
setattr(m,'print2',printing)
m.print2()
try:
#delattr(m,'copy')
#print name
#print dfdf
#print tttt
print m
except AttributeError,e:
print 'something wrong..',e
except Exception,e:
print e
finally:
print '-----------'
#else:
# print "print nothing wrong ...."
執行腳本結果如下:
faxing....
printing....
<__main__.myClass object at 0x028211D0>
-----------
執行個體2
#/usr/bin/env python
import sys
class WebServer(object):
def __init__(self,host,port):
self.host = host
self.port = port
def start(self):
print "Server is starting..."
def stop(self):
print "Server is stopping..."
def restart(self):
self.stop()
self.start()
if __name__ == "__main__":
server = WebServer('localhost',80)
#print sys.argv[1]
cmd_dic = {
'start':server.start,
'stop':server.stop,
'restart':server.restart,
}
#if sys.argv[1] == 'start':
if sys.argv[1] in cmd_dic:
cmd_dic[sys.argv[1]]()
D:\Python學習\腳本學習>python 反射01.py start
Server is starting...
修改上面的腳本如下:
if hasattr(server,sys.argv[1]):
func = getattr(server,sys.argv[1]) ##擷取server.start的記憶體位址
func() ##相當于server.start()
D:\Python學習\腳本學習>python 反射02.py start
D:\Python學習\腳本學習>python 反射02.py stop
Server is stopping...
def test_run(name):
print "running...",name
setattr(server,'run',test_run) ##test_run以run身份綁定到server執行個體中
server.run('peng') ##類似執行test_run('peng')
D:\Python學習\腳本學習>python 反射03.py start
running... peng
def test_run(self,name):
print "running...",name,self.host
server.run(server,'peng') ##類似執行test_run('peng')
D:\Python學習\腳本學習>python 反射04.py start
running... peng localhost
delattr(WebServer,'start')
print server.restart()
#setattr(server,'run',test_run) ##test_run以run身份綁定到server執行個體中
#server.run(server,'peng') ##類似執行test_run('peng')
D:\Python學習\腳本學習>python 反射05.py restart
Server is stopping... ---》執行的是func()的調用
Server is starting... ---》執行的是func()的調用
Server is stopping... ---》執行的是server.restart()的調用
Traceback (most recent call last):
File "反射05.py", line 31, in <module>
print server.restart()
File "反射05.py", line 19, in restart
self.start()
AttributeError: 'WebServer' object has no attribute 'start' ---》執行的是server.restart()的調用,此時start已經删除,是以報了“'WebServer' object has no attribute 'start'”錯誤!!!
版權聲明:原創作品,如需轉載,請注明出處。否則将追究法律責任
本文轉自 鵬愛 51CTO部落格,原文連結:http://blog.51cto.com/pengai/1933012