这个问题在这里已经有了答案:
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/