unbundlocalerror:局部变量…在赋值之前引用

2024-04-28 07:08:40 发布

您现在位置:Python中文网/ 问答频道 /正文

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)

错误: makereq中第8行的文件“C/Python27/btctest.py” hmac=str(hmac.new(secret,散列数据,sha512)) unbundlocalerror:赋值前引用的局部变量“hmac”

有人知道为什么吗?谢谢


Tags: pathkeynewdatabasesecrethashurllib2
2条回答

您正在重新定义函数范围内的hmac变量,因此import语句中的全局变量不在函数范围内。重命名函数scopehmac变量应该可以解决您的问题。

如果在函数中的任意位置分配变量,则该变量将被视为该函数中的局部变量everywhere。因此,您将看到与以下代码相同的错误:

foo = 2
def test():
    print foo
    foo = 3

换句话说,如果函数中存在同名的局部变量,则无法访问全局或外部变量。

要解决这个问题,只需给局部变量hmac一个不同的名称:

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)

注意,可以通过使用globalnonlocal关键字来更改此行为,但似乎您不希望在您的案例中使用这些关键字。

相关问题 更多 >