简体   繁体   中英

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.

I'm using a Velleman K8055 USB experiment board, which has a python module that I'm importing.

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.

I'm having a hard time figuring out how to access the previously initialised instance of the K8055 from within my sub-modules/packages...

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:

from pyk8055 import k8055
k = k8055(0)

I'd like to be able to access the same instance of 'k' from places like:

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?

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). 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.

In case you cannot edit puk8055 module, create your own, call it ie globals.py:

from pyk8055 import k8055
k = k8055(0)

After that in other modules instead directly importing pyk8055, just import your module globals.py:

from globals import k

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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