我从一本书上读到如下代码,但没有解释。 如您所见,在我调用该函数之前,不存在任何变量。 但是在函数调用之后,var2 被弹出堆栈并从我们的 func_a 命名空间中删除,正如我们所期望的那样。但是,var1 仍然存在!!!
How to explain this phenomenon? Is var1 a special kind of variable?
def func_a():
func_a.var1 = 1
var2 = 2
>>> func_a.var1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'function' object has no attribute 'var1'
>>> var2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'var2' is not defined
>>> func_a()
>>> func_a.var1
1
>>> var2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'var2' is not defined
最佳答案
How to explain this phenomenon? Is var1 a special kind of variable?
是的,var1
是一种特殊的变量。或者更准确地说,它根本不是一个变量。它是一个对象的属性(即使该对象是一个函数)。该对象在函数调用之前存在,并且在之后继续存在。
在函数调用中,您向全局对象添加属性,而不是在局部范围内创建变量。
关于python - 为什么函数调用完成后变量仍然存在-python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39760910/