在函数内部分配变量:奇怪的行为

par*_*cer 2 python

我很少使用Python,因此我不清楚为什么允许这样的行为:没有w对象因此它没有s属性,那么为什么f允许进行w.s赋值?

>>> def f():
    w.s="ads"  #allows, no exception
>>> w.s="sds"  #outside function
Traceback (most recent call last):
  File "<pyshell#74>", line 1, in <module>
    w.s="sds"
NameError: name 'w' is not defined
Run Code Online (Sandbox Code Playgroud)

lim*_*mbo 5

尝试运行您的功能,看看会发生什么.在编写代码时Python不会捕获它,但是一旦运行代码就会出错.

你看到的是因为python不知道当你的函数运行时,将不会有一个w具有属性的对象s.但是,当您在函数调用之外执行此操作时,它会检查w范围中是否存在错误.

试试这个:

def f():
    w.s = "one"
w.s  = "one" # called before there is such an object
f() # called before w exists, it will error out    

class SomeClass(object):
    def __init__(self):
        self.s = "two"

w = SomeClass()
f() # since w exists it will run
Run Code Online (Sandbox Code Playgroud)