我有以下结构:
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
。我不想将 d
从 hello
传递到 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/