【问题标题】:What does @object.method do in Python?@object.method 在 Python 中做了什么?
【发布时间】:2019-08-27 09:38:48
【问题描述】:

来自this example

@app.callback(
    dash.dependencies.Output('output-container-button', 'children'),
    [dash.dependencies.Input('button', 'n_clicks')],
    [dash.dependencies.State('input-box', 'value')])
def update_output(n_clicks, value):
    return 'The input value was "{}" and the button has been clicked {} times'.format(
        value,
        n_clicks
    )

我发现这被称为“装饰器”,根据this answer,最常见的是@property@classmethod@staticmethod

这个例子不是这些。 app 是一个已经存在的对象。那么,从语法上讲(我正在寻找 Python 答案,而不是 Dash 答案),@object.method 是做什么的?

【问题讨论】:

  • 和其他装饰器一模一样? @one.two.three.whatever也可以,变化不大。
  • A decorator 只是一个返回另一个函数的函数(或可调用函数)。定义此类函数的方式或位置没有区别。

标签: python decorator python-decorators


【解决方案1】:

这也是一个装饰器,一个装饰器被应用在一个函数上并且可以接受额外的参数。

如果你有一个函数

def multiply_all_args(f, x):
  def new_f(*args, **kwargs):
    return f(*[x*a for a in args], **{k: x*v for k, v in kwargs})
  return new_f

然后做

@multiply_all_args(x=42)
def g(x=1):
  print(x)

is the same as doing
def g(x=1):
  print(x)
g = multiply_all_args(g, x=42)

在您的情况下,这正是发生的情况,因此您的代码等效于

def update_output(n_clicks, value):
    return 'The input value was "{}" and the button has been clicked {} times'.format(
        value,
        n_clicks
    )
update_output = app.callback(update_output,
    dash.dependencies.Output('output-container-button', 'children'),
    [dash.dependencies.Input('button', 'n_clicks')],
    [dash.dependencies.State('input-box', 'value')])

【讨论】:

  • 不应该是update_output = app.callback(...)(update_output)吗?
  • 在链接的示例中,似乎我们定义了update_output,但没有调用它。那是怎么回事?
  • 就是这样,你给的代码只定义了update_output,没有调用它。
猜你喜欢
  • 2019-01-13
  • 2020-10-13
  • 2018-12-04
  • 2011-03-10
  • 1970-01-01
  • 2013-07-09
  • 2011-06-18
  • 2020-05-23
  • 2020-03-19
相关资源
最近更新 更多