为什么下面的 python 代码不会抛出错误? [关闭]

问题描述 投票:0回答:1

即使函数

two()
定义在下面
one()
这使得它超出范围,第 3 行如何执行?!

def one():
    temp = "I am Aditya"
    return two
    
def two(temp):
        return "Hello "+temp

x = one
print(x()("Akshay"))

输出: 你好阿克谢

python oop scope
1个回答
0
投票

问题

def one():
    temp = "I am Aditya"
    return two

函数中定义的变量

one()
仅包含在函数范围内。 当 python 到达行
return two
时,您认为 python 会引发错误,因为
two
在函数范围内不存在。

但是,如果找不到变量,python 将上升 1 级进入对象

two
存在的全局范围,这样就可以了。

如果你在定义

one()
之前尝试调用
def two(): 
,你会得到一个错误。

如果您在定义

one()
之后尝试调用
def two(): 
,没问题。要了解原因,请阅读下文。

背景说明

在python中,一切皆对象。一个函数是一个“对象”,一个变量

temp
也是str类的一个对象,等等

def two(temp):
        return "Hello "+temp


if __name__ == '__main__':
    print(two)
    print(two('sam'))

如果你运行代码,你会看到这个

<function two at 0x10ace2020>
Hello sam
[Finished in 51ms]

对象

two
是一个函数。在对象上使用
print()
将显示指向该对象的引用指针。

你必须使用括号

two()
来执行该功能。然后,你将执行代码返回
Hello sam

要回答您的问题,您需要更深入地了解 python 的工作原理。希望你能明白。干杯:)

© www.soinside.com 2019 - 2024. All rights reserved.