我有:
file1
file2
file3
每个file1 file2 file3,有一个字典叫foo .
我有一个名为example_file的不同文件,它想从file1, file2, file3中读取。
from file1 import foo
from file2 import foo
from file3 import foo
# do something with file1.foo
# do something with file2.foo
# do something with file3.foo
是否有办法通过循环来做到这一点?
for dynamic_name in something:
dynamic_name.foo # do something with foo
# dynamic_name resolves to file1, file2, file3 through the loop
本质上,我想使用导入文件中的文件名来引用文件本身中的项。
这可能吗?
小心使用
from file1 import foo
from file2 import foo
from file3 import foo
因为foo这个名字每次都会被重新分配,到最后它只会指向file3.foo
。
语法something.ofthis
的任何内容都是具有ofthis
属性的对象something
。不管something
是某个类还是模块。您可以通过执行getattr(something, 'ofthis')
来实现相同的目标。您还可以使用dir(something)
来查看您的对象具有哪些可用属性。
import file1, file2, file3
for f in (file1, file2, file3):
foo = getattr(f, 'foo')
内置的__import__
函数将允许您导入名称在变量中的模块。
要了解其工作原理,请考虑以下示例:
# This...
import file1
# ...is the same as this...
file1 = __import__('file1')
# ...and this
name = 'file1'
file1 = __import__(name)
如果要从模块(from ... import ...
)导入名称该怎么办?将您想要导入的名称传递给fromlist
参数。
# This ...
from file1 import foo
# ... is the same as
file1 = __import__('file1', fromlist=['foo'])
foo = file1.foo
如果你有一个模块名称列表,你可以遍历它们。
names = ['file1', 'file2', 'file3']
for name in names:
module = __import__(name, fromlist=['foo'])
foo = module.foo
# Do something with foo
或者你可以保留一个名字和模块的字典。
names = ['file1', 'file2', 'file3']
modules = {}
for name in names:
modules[name] = __import__(name, fromlist=['foo'])
modules['file2'].foo # access like this