Python 局部变量';uuid';分配前参考
我有一个Twisted应用程序,需要在其中生成唯一的ID。如果我导入uuid,然后尝试Python 局部变量';uuid';分配前参考,python,Python,我有一个Twisted应用程序,需要在其中生成唯一的ID。如果我导入uuid,然后尝试str(uuid.uuid4()),它会显示“exceptions.UnboundLocalError:赋值前引用的局部变量'uuid' 如果我将uuid作为myuuid导入 究竟是什么原因造成的?是否有一种扭曲的方式可以直接使用uuid而不是uuid模块?不要害怕Python的交互式解释器: >>> import uuid >>> def foo(): ... uu
str(uuid.uuid4())
,它会显示“exceptions.UnboundLocalError:赋值前引用的局部变量'uuid'
如果我将uuid作为myuuid导入
究竟是什么原因造成的?是否有一种扭曲的方式可以直接使用uuid而不是uuid模块?不要害怕Python的交互式解释器:
>>> import uuid
>>> def foo():
... uuid = uuid.uuid4()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'uuid' referenced before assignment
>>> def bar():
... uuidValue = uuid.uuid4()
...
>>> bar()
>>>
>>> someGlobal = 10
>>> def baz():
... someGlobal = someGlobal + 1
...
>>> baz()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in baz
UnboundLocalError: local variable 'someGlobal' referenced before assignment
>>> def quux():
... someLocal = someGlobal + 1
...
>>> quux()
>>>
导入uuid
>>>def foo():
... uuid=uuid.uuid4()
...
>>>foo()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第2行,在foo中
UnboundLocalError:分配前引用的局部变量“uuid”
>>>def bar():
... uuidValue=uuid.uuid4()
...
>>>bar()
>>>
>>>someGlobal=10
>>>def baz():
... someGlobal=someGlobal+1
...
>>>baz()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第2行,在baz中
UnboundLocalError:赋值前引用的局部变量“someGlobal”
>>>def qux():
... someLocal=someGlobal+1
...
>>>quux()
>>>
只要做一点实验,它就能告诉你很多事情。不要害怕Python的交互式解释器:
>>> import uuid
>>> def foo():
... uuid = uuid.uuid4()
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'uuid' referenced before assignment
>>> def bar():
... uuidValue = uuid.uuid4()
...
>>> bar()
>>>
>>> someGlobal = 10
>>> def baz():
... someGlobal = someGlobal + 1
...
>>> baz()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in baz
UnboundLocalError: local variable 'someGlobal' referenced before assignment
>>> def quux():
... someLocal = someGlobal + 1
...
>>> quux()
>>>
导入uuid
>>>def foo():
... uuid=uuid.uuid4()
...
>>>foo()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第2行,在foo中
UnboundLocalError:分配前引用的局部变量“uuid”
>>>def bar():
... uuidValue=uuid.uuid4()
...
>>>bar()
>>>
>>>someGlobal=10
>>>def baz():
... someGlobal=someGlobal+1
...
>>>baz()
回溯(最近一次呼叫最后一次):
文件“”,第1行,在
文件“”,第2行,在baz中
UnboundLocalError:赋值前引用的局部变量“someGlobal”
>>>def qux():
... someLocal=someGlobal+1
...
>>>quux()
>>>
只要做一点实验,它就能告诉你很多事情。这条评论与Twisted完全无关;这纯粹是Python,这个评论与Twisted完全无关;这纯粹是Python。