python - 在模块函数调用之间存储状态

标签 python python-3.x function global-variables

我有以下结构:

app/
  test1.py
  test/
   __init__.py
   test2.py

我在 test1.py 中导入 test2.py 并使用 test2.py 中的函数

代码如下:

test1.py:

import test.test2 as T


T.hello()
...
T.hello1()

test2.py:

d = {}
def hello():
    print('hi')
    global d
    d['1'] = 1


def hello1():
    print('hi1')
    global d
    print(d) # prints{'1': 1} 

test1.py 将调用 hello 并在一段时间后调用 hello1。我想填充 hello 中的 dict d 并在 hello1 中使用它。使用 global 效果很好,但是有什么更好的方法来做到这一点,因为我想避免 globals 。我不想将 dhello 传递到 test1 中的 caller,然后从那里返回到 你好1

我该怎么做才能避免全局。我正在使用python 3.5

最佳答案

你可以只使用一个类:

class Whatever(object):
    def __init__(self):
        self.d = {}

    def hello(self):
        print('hi')
        self.d['1'] = 1

    def hello1(self):
        print('hi1')
        print(self.d)

_Someinstance = Whatever()
hello = _Someinstance.hello
hello1 = _Someinstance.hello1

您还可以在需要的地方创建并使用实例,而不是最后三行。包含这些只是为了使其行为(几乎)像您的原始版本一样。

请注意,函数也是对象,因此您可以将变量分配给 hello 函数:

def hello():
    print('hi')
    hello.d['1'] = 1

def hello1():
    print('hi1')
    print(hello.d) # prints{'1': 1} 

hello.d = {}

关于python - 在模块函数调用之间存储状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45572152/

相关文章:

python - 试图用 pandas 子集替换 open(),但出现 __exit__ 错误?

python - 将带有音乐的 Python 3.6.1 俄罗斯方 block 游戏转换为 exe

python - 在 python 中的 .txt 文件的新行中添加新列表

function - Go中区分函数和方法的具体原因是什么?

function - 云函数部署问题

python - 为什么我使用 python sklearn 从看似非随机的代码中得到随机结果?

python - 使用 gspread python 在 Google Sheets 的最后一个填充行之后添加数据

Python:求和的 Lambda

python - 在 plotly 中自定义图例的顺序

c++ - 阿克曼表生成器