python - 仅给定闭包函数,如何访问闭包变量?

标签 python python-3.x closures

这个问题在这里已经有了答案:





Reflect / Inspect closed-over variables in Python

(3 个回答)


1年前关闭。




在以下示例中:

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__但它既不在。

最佳答案

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

func.__closure__[0].cell_contents

关于python - 仅给定闭包函数,如何访问闭包变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58468461/

相关文章:

python - 如何将一系列任务路由到 celery 中的特定队列?

python - 删除反向重复项

javascript - 有人可以解释这个 javascript 闭包是如何工作的吗?

groovy - 在 groovy 中查找闭包的自由变量的列表/映射

python - 无法使用 Python 通过 Robot Framework 连接到 localhost :xxxx from session not created: Chrome version must be >= 69. 0.3497.0 上的 chrome

python - Pandas 如何循环遍历 MultiIndex 系列

python - 您将如何在 Python 中绘制此 3D 可视化图?

python - 在python中将列的每个值从str转换为list

python-3.x - 如何通过从特定列创建分组多标题来 reshape 数据框?

javascript - 如何更改闭包干扰 JavaScript 中的预期结果?