【问题标题】:How to access closed over variables given only the closure function? [duplicate]仅给定闭包函数,如何访问已关闭的变量? [复制]
【发布时间】:2020-02-16 11:45:59
【问题描述】:

在下面的例子中:

def speak(volume):
    def whisper(text):
        print(text.lower() + ('.' * volume))
    def yell(text):
        print (text.upper() + ('!' * volume))
    if volume > 1:
        return yell
    elif volume <= 1:
        return whisper


func = speak(volume=10)
func('hello')
HELLO!!!!!!!!!! # <== obviously `10` is stored in `func` somewhere

鉴于func,我将如何获得“音量”? func 命名空间中是否有东西给出了10 的值?我想也许它会在 func.__globals__func.__dict__ 但它不在。

【问题讨论】:

  • 您可以随时将volume 变量设为全局变量
  • 查看stackoverflow.com/a/14414638/2958070 以了解__closure__ 属性的用法
  • 状态变量可能由于某种原因被隐藏了。也许尝试访问它们不是一个好主意?

标签: python python-3.x closures


【解决方案1】:

下面(下面的代码返回10)

func.__closure__[0].cell_contents

【讨论】:

猜你喜欢
  • 1970-01-01
  • 2013-04-24
  • 2013-04-24
  • 2018-03-21
  • 2022-01-24
  • 1970-01-01
  • 2011-04-11
  • 2021-05-28
  • 1970-01-01
相关资源
最近更新 更多