我正在学习 python 命名空间和范围,为此我正在关注 This教程。它以预测以下代码将输出什么的挑战结束。
a = 'global'
def outer():
def len(in_var):
print('called my len() function: ', end="")
l = 0
for i in in_var:
l += 1
return l
a = 'local'
def inner():
global len
nonlocal a
a += ' variable'
inner()
print('a is', a)
print(len(a))
outer()
print(len(a))
print('a is', a)
我对上面代码块的问题是:我们怎么可能在外层()中调用 len() 函数?那么,为什么print(len(a)) 在outer() 中调用len() 函数?
当我尝试调用嵌套函数时,就像我在下面所做的那样,它不起作用。有人可以启发我吗?:
print("Does my Inner get called automatically if I call my outer?")
def outer():
def inner():
print("Yes")
outer() #A call to outer does not call inner() automatically
print(inner()) #Gives a NameError
最佳答案
b() 函数的作用域定义在 a() 函数内部。这意味着,它位于 a() 内。每当我们离开 a() 时,b() 就会被销毁。因此它仅在该范围内可用。除此之外,它不可用。
def a():
def b():
print("inside b")
b() // no error
a()
b() // error. As you are trying to access something which is not available there.
关于python - 我怎么可能在外层()函数中调用嵌套的 len() 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54735047/