How to split a Python module into multiple files?

杀马特。学长 韩版系。学妹 提交于 2019-12-05 00:38:11

modA.py:

class A(...):
   ...

modA1.py:

import modA
class A1(modA.A):
   ...

modA2.py:

import modA
class A2(modA.A):
   ...

modfull:

from modA import A
from modA1 import A1
from modA2 import A2

Even if A "processes" A1s and A2s you should be fine because thanks to duck typing you don't need to import the actual names.

How can I split this file with despite a circular dependency?

Option 1: break the cycles: Put the base class in its own module, the derived classes in additional modules, and functions operating on those derived classes in yet another module.


Option 2: Ignore the cycles, import only modules/packages into the global namespace, IE:

foo.py

class Bar:
    "Frobs Quuxen"

Should never be imported as from foo import Bar, just use import foo and refer to foo.Bar in functions as needed.

I think the core of your question is that you don't want

a.py to imports a1
if
a1.py imports a.

However, that's totally fine in python. However, do make sure that you don't have any code outside of functions/classes in a system with multiple modules, because the order that that runs in will vary based on where you import it, what that imports, the phase of the moon, etc.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!