【问题标题】:What does the @ symbol do in iPython/Python [duplicate]@符号在iPython / Python中做了什么[重复]
【发布时间】:2013-11-19 14:01:51
【问题描述】:

我正在阅读的代码使用@batch_transform@ 符号有什么作用?是 ipython 特有的吗?

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

【问题讨论】:

    标签: python python-2.7 ipython ipython-notebook zipline


    【解决方案1】:

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

    Python 装饰器是对 Python 语法的特定更改,它允许我们更方便地更改函数和方法(可能还有未来版本中的类)。这支持 DecoratorPattern 更具可读性的应用程序,但也支持其他用途

    也看看documentation:

    一个函数定义可以被一个或多个装饰器表达式包装。定义函数时,在包含函数定义的范围内评估装饰器表达式。结果必须是可调用的,它以函数对象作为唯一参数进行调用。返回值绑定到函数名而不是函数对象。多个装饰器以嵌套方式应用

    【讨论】:

    【解决方案2】:

    它是一个装饰器。 Python 装饰器。

    函数、方法或类定义前面可能有一个称为装饰器的@ 特殊符号,其目的是修改后面定义的行为。

    装饰器用@ 符号表示,并且必须放在一个单独的行上,紧挨在相应的函数、方法或类之前。这是一个例子:

    class Foo(object):
        @staticmethod
        def bar():
            pass
    

    另外,你可以有多个装饰器:

    @span
    @foo
    def bar():
        pass
    

    这是一个good lesson。这是great thread on it for SO

    【讨论】:

      【解决方案3】:

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

      例子

      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它!

      【讨论】:

      • 我想你的意思是return wrapper,否则你会创造出……一个黑洞什么的。
      • @rodrigo,是的,你是对的
      猜你喜欢
      • 2013-09-15
      • 2020-03-19
      • 2014-02-07
      • 2015-12-03
      • 1970-01-01
      • 2017-12-20
      • 1970-01-01
      • 2012-02-26
      • 2011-01-02
      相关资源
      最近更新 更多