@符号在iPython / Python中的作用是什么

What does the @ symbol do in iPython/Python

本问题已经有最佳答案,请猛点这里访问。

我正在阅读的代码使用@batch_transform@符号的作用是什么?这是伊普敦的具体情况吗?

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

@语法表示batch_transform是一个python修饰器,请在wiki中阅读更多有关它的信息,并引用:

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

这是一个很好的教训。这是一条很好的线索。


任何函数都可以使用decorator@符号包装。

例子

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

[注]甚至classmethodstaticmethod都是使用python中的装饰器实现的。

在您的例子中,有一个名为batch_transform的函数,您有imported它!