我是 Python 新手,所以我不确定函数定义之前或之后变量赋值的差异。
具体来说,第一个例子是从Lutz的书中采用的。
def tester(start):
print("inside tester")
def nested(label):
print("inside nested")
print(label,nested.state)
nested.state += 1
print("done with nested")
nested.state = start
print("done with tester")
return nested
F = tester(0)
F('spam')
F.state
F.state
代码的目标是在不使用nonlocal
的情况下存储状态信息。
我不确定nested.state
在这里意味着什么。我不确定,因为 nested.state
在 nested()
函数内部使用(即 nested.state +=1
),在 nested 外部使用()
函数(即 nested.state = start
)。
我修改了上面的代码,以查看 Python 是否接受在 nested()
的函数声明之后分配变量,并查看是否缺少与 function.variable
相关的任何概念。 code> 调用(即 nested.state
调用)。
def tester(start):
def nested(label):
print(label, state)
state += 1 #replaced 'nested.state' with 'state' here
state = start #replaced 'nested.state' with 'state' here
return nested
F=tester(0)
F('spam')
F('ham')
不幸的是,上面的代码生成错误赋值前引用了局部变量“state”
。这告诉我,我缺少一些关于 function.variable 的概念(即nested.state)。
有人可以帮我理解三件事吗:
I.为什么带有 nested.state
的代码不会生成任何错误,而 state
却会生成任何错误?
II.nested.state
是什么意思?如果nested.state
是一种访问函数变量的机制,为什么nested()
函数内部的调用也使用nested.state
并且不是状态
?
III. 如果nested.state
是一种访问函数内部变量的机制,那么为什么PyCharm无法在下面显示state
当我输入 nested.
?
如果有任何帮助,我将不胜感激。我研究过,但找不到有关此类问题的任何解释。
最佳答案
第一个代码示例之所以有效,是因为它分配并引用嵌套
函数对象的属性。这里要理解的关键概念是,Python 允许您为对象分配新的任意属性 - 包括函数:
>>> def func(a, b):
return a + b
>>> func(1, 2)
3
>>> func.attr = 5
>>> func.attr
5
第一个代码示例利用了这一事实,使用嵌套
函数对象来存储必要的状态。这与使用任何其他对象来存储状态的概念相同。然而,使用函数特别方便,因为它很容易获得。
在第二个示例中,使用了普通变量。因此,适用正常的范围规则,这意味着 tester
中定义的 state
变量不是 state
嵌套中引用的变量。因此,会引发错误。
关于python - Python中函数定义后的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48016230/