python - 我怎么可能在外层()函数中调用嵌套的 len() 函数

标签 python scope nested namespaces

我正在学习 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/

相关文章:

spring - 嵌套验证组,Spring,JSR 303

python - 在类实例中第二次导入

c - 函数的原型(prototype)类似于在调用例程中声明函数?

python - 如何从异步 pytest 函数测试异步单击命令?

swift - 仍然可以从外部访问私有(private)值

c++ - Visual Assert 的范围问题

mysql - 嵌套 SELECT + INNER JOIN

git - GIT嵌套存储库:Composer与SubModules与Subtree与?

python - 嵌套类装饰器也是描述符类

python - 在 Windows 上微调 GPT-3?