You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在file2.py中调用file1.py里generate_keys函数的want变量?

问题分析与解决方案

问题原因

  • 最初want是generate_keys函数的局部变量,函数外部无法直接访问,因此在file2中调用时触发AttributeError。
  • 改为全局变量后file2显示长度为0,是因为:导入file1时全局变量want初始为空字符串;若file2中访问want的时机早于generate_keys的执行(或赋值逻辑未正常触发),就会读取到初始的空值。

正确解决方案:避免全局变量,返回多值

全局变量会提升代码耦合度、增加调试难度,推荐让generate_keys同时返回生成的keys和want字符串,让file2直接接收所需值。

修改后的file1.py

def randomize_alt(res, start):
    seed = start
    need = ''
    while len(need) != 352:
        if seed >= len(res):
            seed = start + 1
        need += res[seed]
        seed += 2
    return need

def generate_keys(user):
    original_hash = keccak.get_hash_of(user.encode('utf-8')) 
    res = original_hash.decode('utf-8')
    print(f"Some Output: {res}")
    want = randomize_alt(res, 0)
    print("\nThe alternate bits the output: ", want)
    ind = 0; ans = []; tmp = []
    cnt = 0
    keys = []
    while ind < 352:
        string = want[ind:ind+2]
        ind += 2
        tmp.append(int(string, 16))
        if ind % 8 == 0:
            ans.append(tmp)
            tmp = []
            cnt = cnt + 1
        if cnt == 4:
            keys.append(ans)
            cnt = 0
            ans = []
    # 同时返回keys和want
    return keys, want

修改后的file2.py

from file1 import generate_keys

get_keys, get_want1 = generate_keys("SomeInput")
print(f"\n\nThe generated keys for SomeInput are: {get_keys}")

# 获取Pars03对应的结果
key, get_want2 = generate_keys("Pars03")
print(len(get_want2))  # 此时会正确输出352

为什么不推荐用全局变量?

  • 全局变量在多模块、多线程场景下容易被意外覆盖,排查问题难度大。
  • 会降低代码可读性与可维护性,其他开发者难以追踪变量的修改路径。

内容的提问来源于stack exchange,提问作者Ankush Soni

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 18:02:17