跨不同文件脚本的Python全局字典 [英] Python global dict across different file script

查看:406
本文介绍了跨不同文件脚本的Python全局字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你好.我正在尝试使用在main.py中创建的全局dict,在functions.py中调用它. 在我的 main.py 中,

Hello. I am trying to use a global dict created in main.py, which is called in functions.py. In my main.py I have:

import sys,os,...
import functions.py #import my second file

matrix = {}
matrix_do_something
search_the_matrix(value) #which is defined in functions.py

#FILE: functions.py
def search_the_matrix(value):
    global matrix
    if value in matrix:
        return True
    else:
        return False

,我收到此错误:

NameError: global name 'matrix' is not defined

我已阅读 stackoverflow 上的解决方案,将所有内容放到全局文件中,然后从每个文件中调用global.matrix [value],但我不希望这样做.我只想将其称为矩阵,并将其视为我的全局矩阵.这可能吗? 预先谢谢你

I have read a solution on stackoverflow, which says to put everything in a global file and then call from every file global.matrix[value] but I don't want this. I want just call it matrix and think of it as my global matrix. Is this possible? Thank you in advance

推荐答案

在functions.py中,您必须将其导入

In functions.py you would have to import it

from main import matrix

尽管我想为模块命名比main更好的名称.

Though I would want to come up with a better name for my module than main.

如果希望对象在模块/文件中可用,则需要在其中创建或从其他位置导入.

If you want an object to be available in a module / file you need to either create it there or import it from somewhere else.

这篇关于跨不同文件脚本的Python全局字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆