python - 如何仅通过闭包函数访问封闭的变量?
python-3.x closures (1)
这个问题已经在这里有了答案:
- 反映/检查Python中的封闭变量 3个答案
在以下示例中:
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