Python:反射

所謂的反射就是這四個函數:
hasattr(p_object, name)
這個函數是一個布爾型,他的目的就是爲了決定一個對象是否有一個特定的屬性,通常用於訪問某個屬性前先作一下檢查python

getattr(object, name, default=None)
獲取對象的屬性,若是輸方法就返回這個方法對應的地址,試圖獲取不存在的屬性的時候會引起一個AttributeError異常ruby

setattr(p_object, name, value)
給對象的屬性進行賦值,能夠設置一個方法,要麼加入一個新屬性,要麼覆蓋已經存在的屬性markdown

delattr(p_object, name)
從一個對象中刪除屬性
實現函數

#coding:utf-8

import sys
class Webserver(object):
    def __init__(self,host,port):
        self.host=host
        self.port=port

    def start(self):
        print "server is starting....",self.host

    def stop(self):
        print "server is stopping.....",self.host

    def restart(self):
        self.start()
        self.stop()


def run(name):
    print "testing ....",name

def runt(obj,name):
    print obj.host+'...testing...'+name


if __name__ == '__main__':
    execute=sys.argv  #獲取用戶鍵入的參數
    server=Webserver('localhost',8080)
    server2=Webserver('127.0.0.1',80)

如今咱們就來看看用戶經過鍵入參數想要使用類中的方法有幾種代碼實現spa

通常版本rest

#
    if execute[1]=='start':
        server.start()

    if execute[1] == 'stop':
        server.stop()

    if execute[1]=='restart':
        server.restart()

進階版本code

#
    exe={'start':server.start,'stop':server.stop,'restart':server.restart}

    if execute[1] in exe:
        exe[execute[1]]()

最終版本server

hasattr(p_object, name)

getattr(object, name, default=None)

if hasattr(server,execute[1]):   #判斷server是否還有用戶鍵入的方法
        func=getattr(server,execute[1])   #獲取實例方法的地址
        func()  #調用這個方法

setattr(p_object, name, value)

設置屬性對象

setattr(server,'test',run) #將run()函數轉變成實例server中的test()方法
    #執行這個方法
    server.test('cmustard')  #testing .... cmustard

    #進階版屬性,如何讓轉化後的函數能夠使用類屬性,好比說實例中的host屬性
    setattr(server,'testt',runt)
    #只須要將實例顯式的傳遞給函數
    server.testt(server,'cmustard')  
    "localhost...testing...cmustard"

    server2.testt(server2,'cmustard')  
    "'Webserver' object has no attribute 'testt' "
    "因爲這個函數只是傳遞給了實例server,所以其餘實例是沒法使用的"

delattr(p_object, name)

刪除屬性utf-8

#刪除實例server中的host屬性
    delattr(server,'host')
    print server.host 
    "Webserver' object has no attribute 'host'"

    #若是想要刪除方法,
    delattr(server,'start')  #AttributeError: start
    #以上這種是不可行的,由於方法數類屬性,並非實例屬性

    #解決方法
    delattr(Webserver,'start')
    server.start()  #'Webserver' object has no attribute 'start' 刪除成功
相關文章
相關標籤/搜索