从脚本之间的共享静态类中获取值



我有一个带有静态类的主脚本,可以导入其他脚本并将它们存储在上述类中。课程的目的是像脚本之间的接口一样起作用,使他们可以使用类向程序添加功能。在此类中,根据某些事件,它在存储的脚本中称为某些功能,但是在这些脚本中,它们使用主脚本中类中的其他一些函数/变量。我认为作为静态类,它将通过所有脚本共享其属性值,但事实并非如此。试图获得 Interface.scripts.get('foo').a_function()会引起属性,因为脚本中没有" foo"。

我已经完成了我的目标,没有静态属性在类中都没有静态属性,也没有将其唯一的实例传递给脚本的实例作为参数,但是(这是为什么我要这样做(我想为我简化代码,以及每个想编写脚本并仅使用简单的from mainscript import Interface来允许我毫无问题的接口类的人。


这是代码的简历:

mainscript.py

import os
import importlib
class Interface:
    scripts = {}
    @staticmethod
    def init():
        """This function gets called when mainscript is run in terminal:
           python mainscript.py
        """
        for file in os.listdir("./scripts/"):
            if file.endswith(".py"):
                Interface.scripts[file[:-3]] = importlib.import_module(file)
    @staticmethod
    def some_event():
        Interface.scripts.get('bar').do_stuff()
    @staticmethod
    def print_stuff(some_arg):
        print('hello', some_arg)
    ...more code...
if __name__ == '__main__':
    Interface.init()
    Interface.run()  # some loop that handles events, so 'some_event' will be called eventually

bar.py

from mainscript import Interface
def do_stuff():
    Interface.print_stuff('me')
    Interface.scripts.get('foo').a_function()  # AttributeError, foo not in scripts

在其他脚本上相同的情况也会发生相同的错误。请注意,这里的问题是在接口类的属性中共享存储值的内存(例如脚本或任何其他变量(。

那么,我该怎么办?

这是我在这里的第一个问题,所以我希望我可以解释情况。谢谢

请注意,您要保存的内容作为脚本字典中的键,包括.py扩展名,只需剥离它。

Interface.scripts[file[:-3]] = importlib.import_module(file)

我刚刚解决了希望知道的任何人:

我将接口类移至另一个脚本interface.pymainscript.py我导入接口类,就像:

mainscript.py

from interface import Interface
if __name__ == "__main__":
    Interface.init()
    Interface.run()

bar.py和其他脚本中,一切都保持不变。

这样,我保证接口模块仅在mainscript中导入一次,因此诸如bar.py之类的脚本可以进口接口而无需重置接口的类变量(或发生的任何事情(

最新更新