2013-07-25 58 views
0

我正在從urwid提供的wicd應用程序中查看wicd-curses.py文件。有一個名爲wrap_exceptions的函數,然後在文件中的其他幾個地方,我發現了一些類似於這樣的代碼:@wrap_exceptions它發生在幾個其他函數之前。這是什麼意思 ?@代碼構造在Python中意味着什麼?

回答

5

這些被稱爲decorators

裝飾器是接受另一種方法作爲輸入的方法。然後裝飾者會對給定的函數做些什麼來改變輸出。

用數學術語來說,裝飾者可以看起來有點像g(f(x)),其中g是裝飾者,f是要裝飾的原始功能。裝飾者可以對給定的函數執行任何操作,但通常它們會將它們包裝在某種驗證或錯誤管理中。

This blog對裝飾者有很好的解釋;從這樣的一個例子是,在一個簡單的座標系統檢查參數的包裝方法,包括:

class Coordinate(object): 
    def __init__(self, x, y): 
     self.x = x 
     self.y = y 
    def __repr__(self): 
     return "Coord: " + str(self.__dict__) 

def inputChecker(func): 
    def checker(a, b): # 1 
     if a.x < 0 or a.y < 0: 
      a = Coordinate(a.x if a.x > 0 else 0, a.y if a.y > 0 else 0) 
     if b.x < 0 or b.y < 0: 
      b = Coordinate(b.x if b.x > 0 else 0, b.y if b.y > 0 else 0) 
     ret = func(a, b) 
     if ret.x < 0 or ret.y < 0: 
      ret = Coordinate(ret.x if ret.x > 0 else 0, ret.y if ret.y > 0 else 0) 
     return ret 
    return checker 

# This will create a method that has automatic input checking. 
@inputChecker 
def addChecked(a, b): 
    return Coordinate(a.x + b.x, a.y + b.y) 

# This will create a method that has no input checking 
def addUnchecked(a, b): 
    return Coordinate(a.x + b.x, a.y + b.y) 

one = Coordinate(-100, 200) # Notice, negative number 
two = Coordinate(300, 200) 

addChecked(one, two) 
addUnchecked(one, two) 

當座標與addChecked一起添加,它忽略了負數,並假定它是零;其結果是:Coord: {'y': 400, 'x': 300}。但是,如果我們做addUnchecked,我們得到Coord: {'y': 400, 'x': 200}。這意味着在addChecked中,裝飾器的輸入檢查忽略了負值。傳入的變量不會更改 - 只有checker(a, b)內的本地ab會被臨時更正。

編輯:我在博客中添加了一個小的解釋並擴展了其中的一個示例,以響應dkar

+0

請嘗試總結您的答案中最重要的一點,並提供鏈接以供進一步參考。在具體的情況下,簡要解釋裝飾者是什麼。 – dkar

+0

@dkar感謝您的參與。我添加了更多的信息,希望能夠幫助解釋它們是什麼以及如何使用它們。 –