2011-10-11 39 views
0

我想檢查導入的名稱。
代碼:python string to symbolic name

import fst # empty file fst.py 
for s in dir(fst): 
    print(s) # got string with symbolic names 

輸出:

__builtins__ 
__cached__ 
__doc__ 
__file__ 
__name__ 
__package__ 

現在我要檢查每個定義的名稱的值:
代碼:

print(__builtins__) 
print(__cached__) 
print(__doc__) 
print(__file__) 
print(__name__) 
print(__package__) 

問:我如何 「提取物」字符串的符號名稱?
應該代碼:

import fst #empty file fst.py 
for s in dir(fst): 
    print(s, StrToSym(s)) # this call should be equal to str("__name__", __name__) 

回答

2

使用getattr

for s in dir(fst): 
    print (getattr(fst, s)) 
1

使用getattr功能:

print(s, getattr(fst, s)) 
0

有沒有這樣的事情作爲一個 「符號名」。哪個模塊包含的屬性是可用的,所以getattr(module, name)就是你要找的。