說我有:
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
本質上,我想使用匯入中的檔案名來參考檔案本身中的專案。
這可能嗎?
uj5u.com熱心網友回復:
小心
from file1 import foo
from file2 import foo
from file3 import foo
因為名稱 foo 每次都會重新分配,最后它只會指向任何file3.foo內容。
任何語法something.ofthis都是something具有屬性的物件ofthis。不管something是某個類還是模塊。您可以通過執行getattr(something, 'ofthis'). 您還可以使用dir(something)查看您的物件具有哪些可用屬性。
import file1, file2, file3
for f in (file1, file2, file3):
foo = getattr(f, 'foo')
uj5u.com熱心網友回復:
內置__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
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/312964.html
