Python 在模块函数调用之间存储状态
我的结构如下:Python 在模块函数调用之间存储状态,python,python-3.x,function,global-variables,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() d = {} def hello(): print('hi') global d d['1'] = 1 def hello1(): print
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()
d = {}
def hello():
print('hi')
global d
d['1'] = 1
def hello1():
print('hi1')
global d
print(d) # prints{'1': 1}
test2.py:
import test.test2 as T
T.hello()
...
T.hello1()
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
,那么有什么更好的方法可以做到这一点呢。我不想在test1
中将d
从hello
传递到caller
,然后从那里返回到hello1
我可以做些什么来避免
globals
。我使用的是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 = {}
您是否有任何理由避免将两个hello函数都放在一个类中?对于具有实例变量self.d的类,两个具有共享状态的函数似乎是一个明显的用例。
test1.py
文件将进一步导入(与我用于简化的结构相反)因此,我还必须在test1.py
中添加一个类,我想知道是否还有其他方法?将进一步导入test1.py
文件(与我用于简化的结构相反),因此我还必须在test1.py
中添加一个类,这是我试图避免的。为什么?如果您使用的代码与我在回答中使用的代码完全相同,那么它的工作原理应该与原始代码几乎相同。这是因为我添加了行hello=\u Someinstance.hello
和hello1=\u Someinstance.hello1
。如果这不起作用,则需要提供更准确的问题描述:)如果不想使用类,则可以将字典作为每个hello函数的函数参数。只需传入在test1.py中创建的同一个字典,因为字典是通过引用传递的。@csunday95是的,我很想使用这种方法。@mseifer我同意,我的描述不够好,不能保证我为什么要避免使用类。我只是想知道是否有一种不使用类就能做到这一点的明智方法。