What does the @ symbol do in iPython/Python
我正在阅读的代码使用
1 2 3 4 5 6 7 8 9 10 | from zipline.transforms import batch_transform from scipy import stats @batch_transform def regression_transform(data): pep_price = data.price['PEP'] ko_price = data.price['KO'] slope, intercept, _, _, _ = stats.linregress(pep_price, ko_price) return intercept, slope |
A Python decorator is a specific change to the Python syntax that allows us to more conveniently alter functions and methods (and possibly classes in a future version). This supports more readable applications of the DecoratorPattern but also other uses as well
还要查看文档:
A function definition may be wrapped by one or more decorator expressions. Decorator expressions are evaluated when the function is defined, in the scope that contains the function definition. The result must be a callable, which is invoked with the function object as the only argument. The returned value is bound to the function name instead of the function object. Multiple decorators are applied in nested fashion
它是一个装饰工。Python装饰师。
函数、方法或类定义前面可以有一个名为decorator的
修饰符用@符号表示,必须放在相应的函数、方法或类前面的单独一行上。下面是一个例子:
1 2 3 4 | class Foo(object): @staticmethod def bar(): pass |
此外,还可以有多个装饰器:
1 2 3 4 | @span @foo def bar(): pass |
这是一个很好的教训。这是一条很好的线索。
任何函数都可以使用
例子
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | def decor(fun): def wrapper(): print"Before function call" print fun() print"Before function call" return wrapper @decor def my_function(): return"Inside Function" my_function() ## output ## Before function call Inside Function Before function call |
[注]甚至
在您的例子中,有一个名为