2012-08-03 62 views
2

內的詳細信息Twython模塊在內部使用請求模塊。我想在類中修飾方法,但不進行編輯class.py -

我想打包/裝飾請求的方法,所以一切Twython使得request.post(...)調用它將被透明地裝飾/包裝而不會干擾Twython模塊。

如果我編輯的請求代碼庫很容易,但我很好奇如何解決添加裝飾器到已定義函數/方法的一般問題。

import requests 
def magic_wrapper_doodad(...) 
... 
... 
requests.post = magic_wrapper_doodad(my_function, requests.post) # plz? 

import Twython 

# thanks to the above magic, requests.post is wrapped just as if it was defined like: 
@decorator 
def trace(f, *args, **kw): 
    print("calling %s with args %s, %s" % (f.__name__, args, kw)) 
    return f(*args, **kw) 

... 
... #inside requests.py now: 
@trace 
def post(self, *args, **kw): 
... 

我怎麼寫magic_wrapper_doodad() - 或一些替代代碼 - 這樣我就可以裝點這樣的代碼?

回答

5

修飾符@表示法只是調用可裝飾函數調用的裝飾器的語法糖,並將裝飾函數替換爲結果。

換句話說,下面的兩個例子是完全一樣的事情:

@yourdecorator 
def a_function(): 
    pass 

def b_function(): 
    pass 
b_function = yourdecorator(b_function) 

,同樣適用於類定義的方法。

因此,你可以簡單地通過與裝飾的可調用的結果替換類方法修飾類方法:

requests.post = my_function(requests.post) 

這是一樣的,如果你這樣寫:

class requests(object): 
    @my_function 
    def post(self, *args): 
     pass 

請注意,在你的情況requests實際上是一個模塊,而不是一個類,但同樣的原則適用。

+0

s/request/requests – jterrace 2012-08-03 21:56:18

+0

@jterrace:正確插入的's'字符。 – 2012-08-03 21:57:23

+0

請求是一個模塊,但不是一個類。 +1 – jterrace 2012-08-03 21:57:57

2

Martijn Pieters' answer是,如果你需要裝飾的請求函數的路要走。我只是想我會提到,請求確實有a mechanism for hooks

如果你可以用鉤子代替你做什麼,你應該這樣做。它比猴子修補更乾淨。

+0

我知道鉤子,有幾個不同的原因,我想裝飾'request'調用,其中之一是自動添加掛鉤到請求。如何在不修飾request.get' /'request.post'方法或修改'Twython'的代碼的情況下完成這個工作? – 2012-08-04 02:25:40