只导入大型库的某些部分,但为了方便起见隐藏库结构

2024-06-01 09:46:06 发布

您现在位置:Python中文网/ 问答频道 /正文

请看这个例子。有可能做到这一点吗

# 1. importing from a large package lpack
#    only those parts that are going to be used
from lpack import timers    # defines SomeTimer and other Timers
from lpack import triggers  # defines RegularTrigger and others Triggers
# not importing many many other lpack modules

# 2. in the *same .py file* not having to care
#    about the internal organization of the lpack
mytimer = lpack.SomeTimer()        # i.e. not timers.SomeTimer()
mytrigger = lpack.RegularTrigger()

我没有办法。我的想法是lpack = timers + triggers(当然不是字面意思)。自动化的方式(某种预期的进口副作用)将是最好的


Tags: andthetofromimportnotmanyother
1条回答
网友
1楼 · 发布于 2024-06-01 09:46:06

这个怎么样:

from lpack.timers import *   
from lpack.triggers import *

mytimer = SomeTimer()
mytrigger = RegularTrigger()

缺点是,如果两个包都包含同名的方法,其中一个将被覆盖(我希望第二次导入会覆盖第一次导入)。您还应该注意不要使用同名的本地方法,因为这会导致冲突

相关问题 更多 >