轉自:http://blog.sina.com.cn/s/blog_55a11f330100ab1x.html
在Python中,通常情況下,你只能為對象添加一個已經寫好的方法
需求:傳入一個str類型的變量,其值是一個完整的合法的Python函數定義,然后為一個對象添加這個函數:
method_str = u''' def say(self, name) print 'My name is', name '''classMyClass:def __init__(self):passdefextends(self, method_name, method_str):#完成這個方法... obj =MyClass(); obj.extends('say', method_str) obj.say('wendal')#打印出My name is wendal
想了不少路子,在Python的QQ群里面也得到不少靈感,最后順利實現:
defextends(sefl, method_name, method_str):#_method = Noneexec method_str +'''\n_method = %s'''% method_name self.__dict__[method_name]=new.instancemethod(_method,self,None)
簡單解釋一下: method_str在exec前,改變為:
method_str = u''' def say(self, name) print 'My name is', name _method = abc
然后, exec執行后,_method變量就賦值為say函數 接下來,就是Python的自省機制了,通過new模塊,生成特定對象(本例中是self)的實例方法 最后,為特定對象添加say這個函數
恩,這例子,就足以體現出Python在這方面的擴展性 1. method_str是一個字符串,可以動態創建,例如用戶輸出,模板生成 2. 方法的名字可以通過字符串分割等方法獲取到
