简体   繁体   English

导入模块反之亦然

[英]Import Modules vice versa

In MicroPython I created two modules 'mod_a' and 'mod_b'.MicroPython 中,我创建了两个模块“mod_a”和“mod_b”。 I am trying to grab functionality from one to the other and the other way around.我正在尝试从一个到另一个以及相反的方式获取功能。

|mod_a
|  | foo.py
|  | __init__.py
|mod b
|  | baa.py
|  | __init__.py

foo.py foo.py

# necessary to grab module mod_b
import sys
sys.path.append('.')

from mod_b import Baa

class Foo:
    b = Baa()
    b.printer()
    
    def drinker(self):
        print('Drinking')

baa.py baa.py

import sys

# not working
# from mod_a import Foo

class Baa:
    
    def printer(self):
        print('Printer')
        print('b.Baa', sys.path)  => ['.' ...]

        # ==> how to get this working
        # a = Foo()
        # a.drinker()

So far I tried到目前为止我试过

import sys
import os

if '/' not in sys.path:
    sys.path.insert(0, os.getcwd())
    sys.path.insert(1, '.')
    sys.path.insert(2, '/mod_b')
    sys.path.insert(2, '/mod_a')
    sys.path.insert(2, '.mod_b')
    sys.path.insert(2, '.mod_a')

and

sys.modules.get('.mod_b')

Please note that the following code only solves the import problem.请注意,以下代码解决导入问题。 The code still has a circular import problem.该代码仍然存在循环导入问题。

ImportError: cannot import name 'Baa' from partially initialized module 'mod_b.baa' (most likely due to a circular import) (C:\Users\Guest\test\.\mod_b\baa.py) ImportError:无法从部分初始化的模块“mod_b.baa”导入名称“Baa”(很可能是由于循环导入)(C:\Users\Guest\test\.\mod_b\baa.py)

When initializing class Foo, it needs to call Baa.printer() which calls a = Foo() need the uninitialized class Foo, you need to fix that later.初始化 class Foo 时,它需要调用 Baa.printer() 调用 a = Foo() 需要未初始化的 class Foo,您需要稍后修复它。

foo.py foo.py

import sys
sys.path.insert(0,'.')
from mod_b.baa import Baa

class Foo:
    b = Baa()
    b.printer()
    
    def drinker(self):
        print('Drinking')

baa.py baa.py

import sys
sys.path.insert(0,'.')
from mod_a.foo import Foo

class Baa:
    def printer(self):
        print('Printer')
        a = Foo()
        a.drinker()

Circular imports are not supported in MicroPython up to v1.18.直到 v1.18 的 MicroPython不支持循环导入。 MicroPython is largely based on Python 3.4 and differences to Python 3.5 are documented including circular imports. MicroPython 主要基于 Python 3.4,并且记录了与 Python 3.5 的差异,包括循环导入。

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

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