跨文件访问Python全局变量

跨文件访问Python全局变量

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

问题描述

我在一个项目中有三个python文件:

I have three python files in a project:

'''lib.py
   library file that first defines and also accesses a boolean flag'''
vflag = False
...
def lib_method()
  global vflag
  if not vflag:
    do_something_here

'''app.py
   main application that sets the boolean flag defined in lib.py'''
import lib
lib.vflag = method_that_sets_or_resets_vflag()


'''processor.py
   does some processing and needs to access the bool flag'''
from lib import *
...
def processor_method()
  global vflag
  ...
  if vflag:
    do_something_here

我可以在app.py设置/重置标志,但处理器方法无法获得此布尔变量的正确值。

I am able to set/ reset the flag at app.py, but processor method is not able to get the correct value for this boolean variable.

它只获取lib.py开头设置的内容(不是app.py设置的内容)。要求是通过app.py访问运行时设置的值,而不是lib.py初始化它的值

It only gets whatever is set at the beginning of lib.py(not what is set by app.py). The requirement is to access the value set at runtime by app.py, NOT the value to which it was initialized by lib.py

我正在导入不同的lib文件在app.py和processor.py的方式。这有什么不同吗?

I am importing the lib file in different ways at app.py and processor.py. Does that make a difference ?

这可能是一个根本性的错误,所以如果有人能够指出我的具体知识库,我将不胜感激。
此外,它正在弄乱我对全局变量的理解。如果我将变量定义为'global',这是否意味着变量在导入此变量的所有文件(或包含变量定义的文件)中保持为全局变量

It may be a fundamental mistake, so I will appreciate if some one can point me to a specific knowledge base.Also, it is messing with my understanding of global variables. If I define a variable to be 'global', does that mean the variable stays to be a global variable in all the files that import this variable(or the file containing the variable definition)

推荐答案

processor.py 的时>,您正在获取当前在 lib.py 中发生的快照。执行 lib.py 文件,并将所有函数和变量复制并存储在 processor.py 。您没有从 lib.py 存储对原始 vflag 的引用 - 您正在存储一个全新的副本。因此,如果您在 lib.py 中更改 vflag ,则 processor.py 永远不会知道它。

When you use from lib import * in processor.py, you are getting a snapshot of what's going on in lib.py at that moment. The lib.py file is executed, and all of the functions and variables are copied and stored in the namespace of processor.py. You are not storing references to the original vflag from lib.py - you're storing an entirely new copy. So if you change vflag in lib.py, then processor.py will never know about it.

更好的做法是始终使用 import lib ,并且只需访问带 lib.vflag 的变量。您甚至不需要使用全局关键字。

The better practice is to always use import lib, and just access the variable with lib.vflag. You don't even need to use the global keyword.

这篇关于跨文件访问Python全局变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-13 10:07