python - Python 中的装饰器和临时名称绑定(bind)

标签 python

“修饰函数定义不会导致临时名称绑定(bind)”是什么意思?

我现在正在研究Python中的装饰器,这句话让我很困惑。

最佳答案

我认为这意味着在应用装饰器之前,装饰函数实际上从未分配给命名空间中的任何内容。当您使用装饰器编写函数时,您编写的函数将作为参数传递给装饰器,然后装饰器返回的对象将被视为函数。这是一个简单的示例:

def dec(func):
  print('times_two' in globals())
  def _inner(*args, **kwargs):
    print("Decorated")
    return func(*args, **kwargs)
  return _inner

@dec
def times_two(x):
  return x*2

print('times_two' in globals())

你可以看到这个正在运行 heredec 中的 print 表示 False,因为在装饰器完成“装饰”函数之前,名称“times_two”未绑定(bind)到任何内容.

关于python - Python 中的装饰器和临时名称绑定(bind),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47615093/

相关文章:

Python将numpy数组列表转换为二维数组

python - 有没有办法捕获站点使用 python 进行的网络调用?

python - 遍历堆栈(反向列表),是否有 isempty() 方法?

python - 在终端的同一行上以 1 秒的时间增量执行命令

python - index 1/2nd 列表项被无缘无故地跳过

Python - 在 csv 文件中显示具有重复值的行

python - Python 中的 Selenium - 如何单击具有特定标签的所有按钮?

python - 将 mkv 文件转换为 mp4 给我 `filenotfounderror`

python - Pandas - 当 nan 时,从另一个数据帧添加值

python read_fwf 错误 : 'dtype is not supported with python-fwf parser'