商店状态调用

问题描述:

我有以下结构:商店状态调用

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

我导入test2.pytest1.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中填写dictd并在hello1中使用。使用global可以正常工作,但是由于我想避免globals,所以这样做更好。我不想通过dhellocallertest1然后从那里回到hello1

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

+3

你有任何理由,以避免在一类既把你好的功能呢?具有共享状态的两个函数看起来像是一个具有实例变量self.d的类的明显用例。 – csunday95

+0

'test1.py'文件将被进一步导入(与我用于简化的结构相反),所以我将不得不在'test1.py'中添加一个类,并且我想知道是否还有其他办法? – PYA

你可以只使用一个类:

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 = {} 
+0

'test1.py'文件将被进一步导入(与我用于简化的结构相反),所以我将不得不在'test1.py'中添加一个类,这也是我想要避免的。 – PYA

+0

为什么?如果你使用我在答案中使用的代码,它应该几乎和原文一样。这是因为我添加了行'hello = _Someinstance.hello'和'hello1 = _Someinstance.hello1'。如果这不起作用,您需要提供更准确的问题描述:) – MSeifert

+1

如果您不想使用某个类,则可以使字典成为每个hello函数的函数参数。只需传入与test1.py中创建的字典相同的字典即可通过引用传递。 – csunday95