我有以下模塊root_file.py。這個文件包含一些塊。字典從模塊讀取
Name = {
'1':'a'
'2':'b'
'3':'c'
}
在其他文件中,我使用
f1= __import__('root_file')
現在的要求是,我要讀a
id=1
app=Name
print f1[app][id]
,但得到的錯誤閱讀在使用像 變量運行值a,b,c
那
TypeError: unsubscriptable object
我有以下模塊root_file.py。這個文件包含一些塊。字典從模塊讀取
Name = {
'1':'a'
'2':'b'
'3':'c'
}
在其他文件中,我使用
f1= __import__('root_file')
現在的要求是,我要讀a
id=1
app=Name
print f1[app][id]
,但得到的錯誤閱讀在使用像 變量運行值a,b,c
那
TypeError: unsubscriptable object
如何
import root_file as f1
id = 1
app = 'Name'
print getattr(f1, app)[id] # or f1.Name[id]
呃,好吧,如果我明白你正在嘗試做的:
在root_file.py
Name = {
'1':'a', #note the commas here!
'2':'b', #and here
'3':'c', #the last one is optional
}
那麼,在其他的文件:
import root_file as mymodule
mydict = getattr(mymodule, "Name")
# "Name" could be very well be stored in a variable
# now mydict eqauls Name from root_file
# and you can access its properties, e.g.
mydict['2'] == 'b' # is a True statement
是的,只是試圖訪問值 – 2011-04-01 14:39:29
感謝您的工作,我可以告訴我,有什麼區別之間導入root_file爲f1和f1 = __導入__('root_file') – 2011-04-01 14:27:41
前看起來更清潔,不是嗎。 – Shekhar 2011-04-02 05:45:50
多數民衆贊成可以但任何技術差異 – 2011-04-04 09:10:10