以下代码在Python 2.5和3.0中按预期工作:
a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
Run Code Online (Sandbox Code Playgroud)
但是,当我取消注释行(B)时,我得到了UnboundLocalError: 'c' not assigned一行(A).的值a和b被正确地打印.这让我感到困惑,原因有两个:
为什么在行(A)处抛出运行时错误,因为后面的行(B)语句?
为什么变量a和b打印符合预期,同时c引发错误?
我能想到的唯一解释是,赋值创建了一个局部变量,即使在创建局部变量之前,它也优先于"全局"变量.当然,变量在存在之前"窃取"范围是没有意义的.cc+=1c
有人可以解释一下这种行为吗?
码:
import urllib2 as u
import os as o
inn = 'dword.txt'
w = open(inn)
z = w.readline()
b = w.readline()
c = w.readline()
x = w.readline()
m = w.readline()
def Dict(Let, Mod):
global str
inn = 'dword.txt'
den = 'definitions.txt'
print 'reading definitions...'
dell =open(den, 'w')
print 'getting source code...'
f = u.urlopen('http://dictionary.reference.com/browse/' + Let)
a = f.read(800)
print 'writing source code to file...'
f = open("dic1.txt", "w")
f.write(a)
f.close()
j = open('defs.txt', 'w')
print 'finding definition is source …Run Code Online (Sandbox Code Playgroud) 根据python reference manual我们有
如果根本找不到名称,则会引发 NameError 异常。如果名称引用尚未绑定的局部变量,则会引发 UnboundLocalError 异常。UnboundLocalError 是 NameError 的子类。
我不明白什么时候UnboundLocalError抛出?因为
Python 缺少声明并允许名称绑定操作发生在代码块中的任何位置。
那么我们如何才能声明一个变量,而不去初始化她呢?
这似乎是一个非常常见的错误,有几个不同的解决方案, python:UnboundLocalError:在赋值之前引用的局部变量'open'
Python:UnboundLocalError的帮助:在赋值之前引用的局部变量
我的问题不同的地方是我在运行的代码中没有变量"resp".大多数其他问题都已发布,因为海报对类和变量使用了相同的名称,或者未能将其声明为全局变量.
代码
import tweepy
auth = tweepy.OAuthHandler('75VSSMGC4pfUB5u0Zt5G3Q', '2olQeiquDg71uwnGoU2c9e2u3qy2LrKkn2p6KWBIdI')
auth.set_access_token('122095773-cCrYa4FWFoBkx44LES8yeBlt8DTG0jnZivJ79k2J', 'p1Nmp9DaPUIThpTamzIMfdvJu0wgdfxmghdwsSagM')
api = tweepy.API(auth)
print api.rate_limit_status()
#print tweepy.api.rate_limit_status()
Run Code Online (Sandbox Code Playgroud)
错误
Traceback (most recent call last):
File "/Users/brendan/Documents/workspace/Tweeter/src/rate_limit.py", line 6, in <module>
print api.rate_limit_status()
File "build/bdist.macosx-10.5-fat3/egg/tweepy/binder.py", line 185, in _call
File "build/bdist.macosx-10.5-fat3/egg/tweepy/binder.py", line 147, in execute
UnboundLocalError: local variable 'resp' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
有什么建议?