我正在使用urwid提供的wicd应用程序查看文件wicd-curses.py.有一个名为wrap_exceptions的函数,然后在文件的其他几个地方,我发现了一些像@wrap_exceptions这样的代码,它发生在其他几个函数之前.这是什么意思 ?
这些被称为装饰器.
装饰器是接受另一种方法作为输入的方法.然后装饰器将对给定的函数执行某些操作以更改输出.
在数学术语中,装饰器可以看起来有点像装饰器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)
Run Code Online (Sandbox Code Playgroud)
当坐标与其一起添加时addChecked,它会忽略负数并假设它为零; 结果是:Coord: {'y': 400, 'x': 300}.但是,如果我们这样做addUnchecked,我们就会得到Coord: {'y': 400, 'x': 200}.这意味着,在addChecked装饰者的输入检查中忽略了负值.传入的变量不会更改 - 仅暂时更正本地a和b内部checker(a, b).
编辑:我添加了一个小解释,并在博客中的一个示例上进行了扩展,以响应dkar.