Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/338.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python UnboundLocalError:局部变量…;分配前参考_Python_Python 2.7 - Fatal编程技术网

Python UnboundLocalError:局部变量…;分配前参考

Python UnboundLocalError:局部变量…;分配前参考,python,python-2.7,Python,Python 2.7,错误: makereq中的文件“C:/Python27/btctest.py”,第8行 hmac=str(hmac.new(secret,hash_数据,sha512)) UnboundLocalError:赋值前引用的局部变量“hmac” 有人知道为什么?谢谢您正在函数范围内重新定义hmac变量,因此import语句中的全局变量不在函数范围内。重命名函数作用域hmac变量应该可以解决您的问题。如果在函数中的任何位置分配变量,则该变量在该函数中的任何位置都将被视为局部变量。因此,您将在以下代码中

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


有人知道为什么?谢谢

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

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

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)
换句话说,如果函数中存在同名的局部变量,则无法访问全局变量或外部变量

要解决此问题,只需为局部变量
hmac
指定一个不同的名称:

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

注意,这种行为可以通过使用
global
nonlocal
关键字来改变,但您似乎不想在您的案例中使用这些关键字。

如果我错了,请纠正我,但是
nonlocal
仅是Python 3+,不是?OP将其标记为2.7。
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)