【问题标题】:UnboundLocalError: local variable … referenced before assignmentUnboundLocalError:局部变量……在赋值之前引用
【发布时间】:2013-06-13 21:19:52
【问题描述】:
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 行,在 makereq hmac = str(hmac.new(秘密,hash_data,sha512)) UnboundLocalError:赋值前引用了局部变量“hmac”

有人知道为什么吗?谢谢

【问题讨论】:

    标签: python python-2.7


    【解决方案1】:

    如果您在函数中的任何位置分配给变量,则该变量将被视为该函数中的局部变量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 关键字更改此行为,但您似乎不想在您的情况下使用它们。

    【讨论】:

    • 如果我错了,请纠正我,但nonlocal 仅适用于 Python 3+,不是吗? OP 标记了这个 2.7。
    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 2011-05-02
      • 1970-01-01
      • 2012-11-14
      • 2013-11-29
      • 2019-09-02
      • 1970-01-01
      • 2015-06-14
      • 2018-06-29
      • 2011-10-31
      相关资源
      最近更新 更多