2009-09-14 95 views

回答

3

是的,這是可能的,但有幾個問題。 首先,你明白地從類中得到一個方法,你得到一個修飾器對象,但不是函數本身。

class X(object): 
    def m(self,x): 
     print x 

print X.m   #>>> <unbound method X.m> 
print vars(X)['m'] #>>> <function m at 0x9e17e64> 

def increase_decorator(function): 
    return lambda self,x: function(self,x+1) 

其次,我不知道,如果設置新的方法將總是工作:

x = X() 
x.m(1)   #>>> 1 
X.m = increase_decorator(vars(X)['m']) 
x.m(1)   #>>> 2 
7

不要這樣做。

使用繼承。

import some_module 

class MyVersionOfAClass(some_module.AClass): 
    def someMethod(self, *args, **kwargs): 
     # do your "decoration" here. 
     super(MyVersionOfAClass, self). someMethod(*args, **kwargs) 
     # you can also do "decoration" here. 

現在,收拾你的主程序使用MyVersionOfAClass,而不是some_module.AClass

+1

這是我看待這個問題的原始方式,但這是很多工作。接受答案中的方法對知道有用 - 即使它不是最正確的做事方式。 – 2009-09-14 13:20:54

+1

這不是一個「更正確」的問題,而是「可讀」和「可維護」問題。你的用例是OO語言繼承的確切原因。它可能表現爲很多工作,但這是每個其他程序員期望看到的。從長遠來看,有趣的動態裝飾者是一種責任。普通的舊遺產不會成爲一項責任。 – 2009-09-14 16:10:47

相關問題