我使用yield来创建一个生成器,该生成器返回使用正则表达式和re.sub()提取的字符串块.虽然我发现了一种有效的方法,但我对它为什么单向工作而不是另一种工作有点困惑,如下所示:
这不起作用(processchunk()没有分配给splitmsg中声明的块):
def splitmsg(msg):
chunk = None
def processchunk(match):
chunk = match.group(1)
return ""
while True:
chunk = None
msg = re.sub(reCHUNK,processchunk,msg,1)
if chunk:
yield chunk
else:
break
Run Code Online (Sandbox Code Playgroud)
这确实有效(注意唯一的区别是块现在是一个列表块):
def splitmsg(msg):
chunks = [ None, ]
def processchunk(match):
chunks[0] = match.group(1)
return ""
while True:
chunks[0] = None
msg = re.sub(reCHUNK,processchunk,msg,1)
if chunks[0]:
yield chunks[0]
else:
break
Run Code Online (Sandbox Code Playgroud)
我的问题基本上是为什么看起来chunk/chunk变量的范围似乎取决于它是一个普通变量还是一个列表?
我试图在python中创建一个类,它读取dropbox的访问密钥/密码然后下载文件.密钥/秘密部分正常工作,但我似乎在识别客户端对象时遇到问题,可能是由于全局变量和局部变量的问题.我无法在其他地方找到答案.
这是我的代码的一部分:
from dropbox import client, rest, session
class GetFile(object):
def __init__(self, file1):
self.auth_user()
def auth_user(self):
APP_KEY = 'xxxxxxxxxxxxxx'
APP_SECRET = 'xxxxxxxxxxxxxx'
ACCESS_TYPE = 'dropbox'
TOKENS = 'dropbox_token.txt'
token_file = open(TOKENS)
token_key,token_secret = token_file.read().split('|')
token_file.close()
sess = session.DropboxSession(APP_KEY,APP_SECRET, ACCESS_TYPE)
sess.set_token(token_key,token_secret)
client = client.DropboxClient(sess)
base, ext = file1.split('.')
f, metadata = client.get_file_and_metadata(file1)
out = open('/%s_COPY.%s' %(base, ext), 'w')
out.write(f.read())
Run Code Online (Sandbox Code Playgroud)
这是错误:
Traceback (most recent call last):
File "access_db.py", line 30, in <module>
start = GetFile(file_name)
File "access_db.py", line 6, in __init__
self.auth_user() …Run Code Online (Sandbox Code Playgroud) 这是我的代码:
x = 1
def poi(y):
# insert line here
def main():
print poi(1)
if __name__ == "__main__":
main()
Run Code Online (Sandbox Code Playgroud)
如果放置4条线,一次一条,代替 # insert line here
Lines | Output
---------------+--------------
1. return x | 1
2. x = 99 |
return x | 99
3. return x+y | 2
4. x = 99 | 99
Run Code Online (Sandbox Code Playgroud)
在上面的行中,似乎在情况1和3中使用了在函数之上声明的全局x
但是,
x = x*y
return x
Run Code Online (Sandbox Code Playgroud)
这给了
error : local variable 'x' is reference before assignment
Run Code Online (Sandbox Code Playgroud)
这里有什么问题?
如果执行以下代码将显示错误消息:
UnboundLocalError:赋值前引用的局部变量'a'
a = 220.0
b = 4300.0
c = 230.0/4300.0
def fun():
while (c > a/b):
a = a + 1
print a/b
if __name__ == '__main__':
fun()
Run Code Online (Sandbox Code Playgroud)
但修改为:
a = 220.0
b = 4300.0
c = 230.0/4300.0
def fun():
aa = a
bb = b
while (c > aa/bb):
aa = aa + 1
print aa/bb
if __name__ == '__main__':
fun()
Run Code Online (Sandbox Code Playgroud)
它会好的.任何建议或指示都会很棒.非常感谢!
import hmac, base64, hashlib, urllib2
base = 'https://.......'
def makereq(key, secret, path, data):
hash_data = path + chr(0) + data
secret = base64.b64decode(secret)
sha512 = hashlib.sha512
hmac = str(hmac.new(secret, hash_data, sha512))
header = {
'User-Agent': 'My-First-test',
'Rest-Key': key,
'Rest-Sign': base64.b64encode(hmac),
'Accept-encoding': 'GZIP',
'Content-Type': 'application/x-www-form-urlencoded'
}
return urllib2.Request(base + path, data, header)
Run Code Online (Sandbox Code Playgroud)
错误:文件"C:/Python27/btctest.py",第8行,在makereq中hmac = str(hmac.new(secret,hash_data,sha512))UnboundLocalError:在赋值之前引用的局部变量'hmac'
有人知道为什么吗?谢谢
根据python reference manual我们有
如果根本找不到名称,则会引发 NameError 异常。如果名称引用尚未绑定的局部变量,则会引发 UnboundLocalError 异常。UnboundLocalError 是 NameError 的子类。
我不明白什么时候UnboundLocalError抛出?因为
Python 缺少声明并允许名称绑定操作发生在代码块中的任何位置。
那么我们如何才能声明一个变量,而不去初始化她呢?
我不太明白以下两个相似代码之间的区别:
def y(x):
temp=[]
def z(j):
temp.append(j)
z(1)
return temp
Run Code Online (Sandbox Code Playgroud)
调用y(2)返回[1]
def y(x):
temp=[]
def z(j):
temp+=[j]
z(1)
return temp
Run Code Online (Sandbox Code Playgroud)
调用y(2)返回UnboundLocalError: local variable 'temp' referenced before assignment.为什么+运算符会生成错误?谢谢
代码1:
# coding:utf-8
sum = 5
def add(x, y):
print sum
sum = x + y
if __name__ == '__main__':
add(7, 8)
Run Code Online (Sandbox Code Playgroud)
当我运行上面的代码时,出现以下错误:
ssspure:python ssspure$ python test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
add(7, 8)
File "test.py", line 6, in add
print sum
UnboundLocalError: local variable 'sum' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
代码2:
ssspure:python ssspure$ python test.py
Traceback (most recent call last):
File "test.py", line 11, in <module>
add(7, 8)
File "test.py", line 6, in add
print …Run Code Online (Sandbox Code Playgroud) 我认为list.extend列表中的"+ ="基本上做同样的事情 - 扩展列表而不创建新列表.
我希望下面的代码可以打印,[42, 43, 44, 45, 46]但我得到了UnboundLocalError: local variable 'x' referenced before assignment
为什么我收到此错误?区别在哪里?
def f():
x.extend([43, 44])
def g():
x += ([45, 46])
x = [42]
f()
g()
print x
Run Code Online (Sandbox Code Playgroud)
我在python2.7.3和python3.4.0中尝试过这个.
可能重复:
Python变量范围问题
Python手册将范围定义为:
范围定义块内名称的可见性.如果在块中定义了局部变量,则其范围包括该块.如果定义发生在功能块中,则作用域将扩展到定义块中包含的任何块,除非包含的块为名称引入了不同的绑定.
我有这个程序:
import random
def f():
a = "Is the scope static?"
if random.randint(0, 1) == 1:
del a
print a
Run Code Online (Sandbox Code Playgroud)
打印失败的可能性为50%:
>>> f()
Is the scope static?
>>> f()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 5, in f
UnboundLocalError: local variable 'a' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
通过这种方式,我认为print语句有50%的可能性超出了'a'的范围,但我可能错了.Python中范围的"正确"解释是什么?Python中变量的范围是静态定义的吗?变量"a"的范围是什么?
python ×10
python-2.7 ×2
append ×1
dropbox-api ×1
generator ×1
list ×1
namespaces ×1
regex ×1
scope ×1
variables ×1
yield ×1