UnboundLocalError:在赋值之前引用的局部变量....

use*_*235 4 python python-2.7

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'

有人知道为什么吗?谢谢

And*_*ark 9

如果你在一个函数赋值给一个变量的任何地方,这个变量将被视为一个局部变量无处不在的功能.所以你会看到与以下代码相同的错误:

foo = 2
def test():
    print foo
    foo = 3
Run Code Online (Sandbox Code Playgroud)

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

要解决此问题,只需为本地变量指定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)
Run Code Online (Sandbox Code Playgroud)

请注意,可以使用globalnonlocal关键字更改此行为,但似乎您不希望在您的情况下使用这些行为.


Sil*_*Ray 2

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