[英]In python how do I access an instance of a class from a parent or top-level module from withing a submodule
我是python新手,并且使用CherryPy Web服务器和Jinja 2模板引擎开发了我的第一个python应用程序。
我正在使用Velleman K8055 USB实验板,该板具有要导入的python模块。
为了使K8055正常运行,我必须在K8055模块中创建该类的实例,然后打开与开发板的连接...据我所知,我必须保持该连接/实例运行,并使用唯一的实例来控制板,即使是在子模块内部也是如此。
我很难弄清楚如何从子模块/软件包中访问K8055的先前初始化的实例...
我的应用程序结构与以下内容非常相似...
SmartyPi/
SmartyPi/smartypi.py
SmartyPi/smartypi/__init__.py
SmartyPi/smartypi/scheduler/
SmartyPi/smartypi/scheduler/__init__.py
SmartyPi/smartypi/scheduler/Scheduler.py
SmartyPi/smartypi/web/
SmartyPi/smartypi/web/__init__.py
SmartyPi/smartypi/web/k8055.py
SmartyPi/smartypi/web/root.py
SmartyPi/smartypi/web/schedule.py
在“ SmartyPi / smartypi.py”中,我使用以下命令初始化了k8055对象的实例:
from pyk8055 import k8055
k = k8055(0)
我希望能够从类似的地方访问相同的'k'实例:
SmartyPi/smartypi/web/k8055.py
SmartyPi/smartypi/web/schedule.py
我似乎无法自行解决...
'SmartyPi / smartypi.py'不是创建我的K8055实例的最佳位置吗?
我应该在其他地方使用它吗?如何根据需要进行这项工作?
向pyk8055模块添加k = k8055(0)(最后)。 比在所有其他模块中只需替换:
from pyk8055 import k8055
与
from pyk8055 import k
注意:我建议使用更独特的名称重命名k。
如果您无法编辑puk8055模块,请创建自己的模块,将其命名为globals.py:
from pyk8055 import k8055
k = k8055(0)
之后,在其他模块中直接导入pyk8055,只需导入模块globals.py即可:
from globals import k
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.