简体   繁体   English

在python中,如何通过父模块或顶级模块访问子类的实例以及子模块

[英]In python how do I access an instance of a class from a parent or top-level module from withing a submodule

I'm a python newbie, and developing my first python app using the CherryPy Web Server and Jinja 2 Templating engine. 我是python新手,并且使用CherryPy Web服务器和Jinja 2模板引擎开发了我的第一个python应用程序。

I'm using a Velleman K8055 USB experiment board, which has a python module that I'm importing. 我正在使用Velleman K8055 USB实验板,该板具有要导入的python模块。

For the K8055 to function properly I have to create an instance of the class within the K8055 module, then open a connection to the board... As far as I understand it I have to keep that connection/instance running, and use that sole instance to control the board, even from within sub-modules. 为了使K8055正常运行,我必须在K8055模块中创建该类的实例,然后打开与开发板的连接...据我所知,我必须保持该连接/实例运行,并使用唯一的实例来控制板,即使是在子模块内部也是如此。

I'm having a hard time figuring out how to access the previously initialised instance of the K8055 from within my sub-modules/packages... 我很难弄清楚如何从子模块/软件包中访问K8055的先前初始化的实例...

I have a Application structure very similar to the following... 我的应用程序结构与以下内容非常相似...

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

In 'SmartyPi/smartypi.py' I have initialised my instance of the k8055 object with: 在“ SmartyPi / smartypi.py”中,我使用以下命令初始化了k8055对象的实例:

from pyk8055 import k8055
k = k8055(0)

I'd like to be able to access the same instance of 'k' from places like: 我希望能够从类似的地方访问相同的'k'实例:

SmartyPi/smartypi/web/k8055.py
SmartyPi/smartypi/web/schedule.py

I can't seem to figure it out on my own... 我似乎无法自行解决...

Was 'SmartyPi/smartypi.py' not the best place to create my K8055 instance? 'SmartyPi / smartypi.py'不是创建我的K8055实例的最佳位置吗?

Should I be making it somewhere else, and how can I make this work as I need it to? 我应该在其他地方使用它吗?如何根据需要进行这项工作?

Add k = k8055(0) to the pyk8055 module (at the end). 向pyk8055模块添加k = k8055(0)(最后)。 An than in all other modules just replace: 比在所有其他模块中只需替换:

from pyk8055 import k8055

with

from pyk8055 import k

Note: I suggest to rename k with something more unique. 注意:我建议使用更独特的名称重命名k。

In case you cannot edit puk8055 module, create your own, call it ie globals.py: 如果您无法编辑puk8055模块,请创建自己的模块,将其命名为globals.py:

from pyk8055 import k8055
k = k8055(0)

After that in other modules instead directly importing pyk8055, just import your module globals.py: 之后,在其他模块中直接导入pyk8055,只需导入模块globals.py即可:

from globals import k

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM