更新时间:2022-12-08 13:32:40
为避免从< whatever>重复 import *
25次,你需要一个循环,例如:
To avoid repeating from <whatever> import *
25 times, you need a loop, such as:
import sys
def _allimports(modnames)
thismod = sys.modules[__name__]
for modname in modnames:
submodname = '%s.%s' % (thismod, modname)
__import__(submodname)
submod = sys.modules[submodname]
thismod.__dict__.update(submod.__dict__)
_allimports('a b c d e'.split()) # or whatever
我将有意义的代码放在函数中因为( a)总是***[[为了性能并避免污染模块的命名空间]],(b)在这种特殊情况下它也避免了事故(例如,某些子模块可能定义名称 thismod
或 modnames
...因此,将我们在循环中使用的名称保留在函数的本地,不是模块非常重要全局,所以他们不会被意外践踏; - )。
I'm putting the meaningful code in a function because (a) it's always best [[for performance and to avoid polluting the module's namespace]], (b) in this particular case it also avoids accidents (e.g., some submodule might define a name thismod
or modnames
... so it's important to keep those names that we're using in the loop local to the function, not module globals, so they can't be accidentally trampled;-).
如果你想强制执行这个事实在名为 modname
的模块中,只有一个具有相同名称的类(或其他全局),将循环的最后一个语句更改为:
If you want to enforce the fact that a module named modname
only has one class (or other global) with the same name, change the last statement of the loop to:
setattr(thismod, modname, getattr(submod, modname))