在 Python 中将文件夹变成模块
我有一个 Python 模块,它正在变得有点失控。我想将它分成更小的文件,以更好地管理我的代码,但我希望它看起来好像没有任何改变。具体来说,假设我在 c.py
中有类 C1
和 C2
。我想创建一个文件夹结构,
c/
__init__.py
c1.py <--- class C1 in here
c2.py <--- class C2 in here
这样我就可以通过以下两种方式使用代码
import c
c1 = c.C1()
c2 = c.C2()
,并且
from c import *
c1 = C1()
c2 = C2()
我已经完成了大部分工作;如果我按如下方式定义 __init__.py
,
from c1 import *
from c2 import *
__all__ == []
那么我可以在两种方式中的第一种中使用 c
。如何以第二种方式使用c
(最好不要枚举__all__
中的所有C1
和C2
)
I have a module in Python that is growing a tad out of hand. I would like to segregate it into smaller files to better manage my code, but I would like it to seem as if nothing has changed. To be concrete, suppose I have the classes C1
and C2
in c.py
. I would like to create a folder structure,
c/
__init__.py
c1.py <--- class C1 in here
c2.py <--- class C2 in here
such that I can use the code in the following two ways
import c
c1 = c.C1()
c2 = c.C2()
and
from c import *
c1 = C1()
c2 = C2()
I've already got most of the way there; if I define __init__.py
as follows,
from c1 import *
from c2 import *
__all__ == []
then I can do use c
in the first of the two ways. How can I use c
in the second fashion (preferably without enumerating all C1
and C2
in __all__
)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
跳过
__init__.py
中的__all__
语句,您将能够使用这两种方法。Skip the
__all__
statement in__init__.py
and you will be able to use both methods.