0

i was looking at a file wicd-curses.py from the wicd application available with urwid. there is a function named as wrap_exceptions and then at several other places in the file i find some code like this @wrap_exceptions which occurs just before several other functions. What does it mean ?

4

1 回答 1

5

这些被称为装饰器

装饰器是接受另一种方法作为输入的方法。然后装饰器将对给定的函数做一些事情以改变输出。

用数学术语来说,装饰器看起来有点像装饰器在g(f(x))哪里,g是要装饰f的原始函数。装饰器可以对给定的函数做任何事情,但通常它们将它们包装在某种验证或错误管理中。

这个博客对装饰器有很好的解释;这里的一个例子是一个包装器方法,它在一个简单的坐标系中检查参数:

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,负值被装饰器的输入检查忽略了。传入的变量没有改变——只是临时修正了局部ab内部。checker(a, b)

编辑:我添加了一个小解释并扩展了博客中的一个示例以响应dkar

于 2013-07-25T22:45:16.047 回答