UnboundLocalError:局部变量……在赋值前被引用 [英] UnboundLocalError: local variable … referenced before assignment
问题描述
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)
错误:文件C:/Python27/btctest.py",第 8 行,在 makereqhmac = str(hmac.new(secret, hash_data, sha512))UnboundLocalError:赋值前引用了局部变量hmac"
Error: File "C:/Python27/btctest.py", line 8, in makereq hmac = str(hmac.new(secret, hash_data, sha512)) UnboundLocalError: local variable 'hmac' referenced before assignment
有人知道为什么吗?谢谢
Somebody knows why? Thanks
推荐答案
如果您在函数中的任何位置分配变量,则该变量将被视为该函数中处处的局部变量.所以你会看到下面的代码出现同样的错误:
If you assign to a variable anywhere in a function, that variable will be treated as a local variable everywhere in that function. So you would see the same error with the following code:
foo = 2
def test():
print foo
foo = 3
换句话说,如果函数中存在同名的局部变量,则无法访问全局或外部变量.
In other words, you cannot access the global or external variable if there is a local variable in the function of the same name.
要解决这个问题,只需给你的局部变量 hmac
一个不同的名字:
To fix this, just give your local variable hmac
a different name:
def makereq(key, secret, path, data):
hash_data = path + chr(0) + data
secret = base64.b64decode(secret)
sha512 = hashlib.sha512
my_hmac = str(hmac.new(secret, hash_data, sha512))
header = {
'User-Agent': 'My-First-test',
'Rest-Key': key,
'Rest-Sign': base64.b64encode(my_hmac),
'Accept-encoding': 'GZIP',
'Content-Type': 'application/x-www-form-urlencoded'
}
return urllib2.Request(base + path, data, header)
请注意,可以通过使用 global
或 nonlocal
关键字来更改此行为,但您似乎不想在您的情况下使用它们.
Note that this behavior can be changed by using the global
or nonlocal
keywords, but it doesn't seem like you would want to use those in your case.
这篇关于UnboundLocalError:局部变量……在赋值前被引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!