[英]Why variable still exists after function call finished -python
I read from a book about some code like below, but it was not explained. 我从一本书中读到了一些类似下面的代码,但是没有解释。 As you can see, before I call the function, no variable exists.
如您所见,在调用函数之前,不存在任何变量。 But after function call, var2 was popped form stack and removed from our namespace of func_a as what we expected.
但是在函数调用之后,var2从窗体堆栈中弹出,并按照我们的预期从func_a的命名空间中删除。 But, var1 still exists!!!
但是,var1仍然存在!!!
How to explain this phenomenon?
如何解释这种现象? Is var1 a special kind of variable?
var1是一种特殊的变量吗?
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是一种特殊的变量吗?
Yes, var1
is a special kind of variable. 是的,
var1
是一种特殊的变量。 Or perhaps more precisely, it's not a variable at all. 或者更确切地说,它根本不是变量。 It's an attribute of an object (even though the object is a function).
它是对象的属性(即使对象是函数)。 The object existed before the function call, and it continues to exist after.
该对象在函数调用之前就存在,并且在调用之后就继续存在。
In the function call you are adding an attribute to a global object rather than creating a variable in a local scope. 在函数调用中,您是在向全局对象添加属性 ,而不是在本地范围内创建变量 。
You are confusing the function namespace with the function object. 您正在将函数名称空间与函数对象混淆。 Before the function is called,
var1
doesn't exist. 在调用该函数之前,
var1
不存在。 When the function is called, python creates a temporary local namespace for that one call. 调用该函数时,python会为该调用创建一个临时的本地名称空间。 When the function hits
var2 = 2
, var2
is created in the local function namespace. 当函数达到
var2 = 2
,将在本地函数名称空间中创建var2
。 When the function hits func_a.var1 = 1
, python looks func_a
up in the global namespace, finds the function object, and adds var1
to it. 当函数达到
func_a.var1 = 1
,python在全局名称空间中查找func_a
,找到函数对象,并向其中添加var1
。 When the function exits, the local namespace disappears but the function object still exists and so will var1
. 当函数退出时,本地名称空间消失,但函数对象仍然存在,
var1
也将存在。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.