gpt4 book ai didi

python - 如何将多个模块分组到一个命名空间中?

转载 作者:太空狗 更新时间:2023-10-29 22:15:21 25 4
gpt4 key购买 nike

我有一个 python3.5 项目,我决定为每个模块创建一个类。我决定这样做是因为我发现我的文件很长而且我很难理解发生了什么。

进行更改后,我觉得我在每个导入文件中都在重复自己:

from school.student import Student
from school.classroom import ClassRoom
from school.teacher import Teacher

有什么办法可以通过重复吗?我希望我的导入更像:

from school import Student, ClassRoom, Teacher

最佳答案

使用 __init__ 模块来完成这个。 __init__ 模块的内容在导入父模块/包时进行评估。像这样:

# __init__.py
from school.student import Student
from school.classroom import ClassRoom
from school.teacher import Teacher

这会将 StudentClassRoomTeacher 带入 school 命名空间。现在您可以根据需要使用 school 模块导入。

注意:以这种方式很容易污染你的命名空间。最好按照开始的方式在每个模块中显式导入,或者使用 this answer 中的方法。并使用采用显式模块引用的类(例如,school.Teacher() 而不是 Teacher())。

如果你觉得 school.Teacher() 太长,你可以这样缩短一些:

import school as sch
teacher = sch.Teacher()

等等等等

但是,另一方面,如果这些类是应该在包级别可用的对象,则将它们导入包命名空间可能是正确的做法。只有你才能下定决心。

关于python - 如何将多个模块分组到一个命名空间中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36556418/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com