2017-03-07 99 views
0

我正在通過許多帖子尋找解決方案,但也許我正在尋找錯誤的短語。我是新來的蟒蛇,我的代碼的問題如下:循環中的動態變量python

from yahoo_finance import Share 
for line in open('fcts.txt'): 
    yahoo = Share('YHOO') 
    print (yahoo +'.' + line) 

它應該基本上做到以下但裏面fcts.txt每一個功能:

from yahoo_finance import Share 
yahoo = Share('YHOO') 
print (yahoo.get_open()) 

fcts.txt包含像

不同的功能
get_open() 
get_change() 
... 

謝謝 Stefan

+0

我不明白你的問題。 fcts.txt中有什麼? Python的功能? – GPhilo

+0

「共享」實例的Python方法的名稱。 – Alfe

+2

爲什麼在你的txt文件中有一些奇怪的半碼......?看起來不太理智。 – deceze

回答

1

您可以按名稱這樣的訪問方法:

from yahoo_finance import Share 

with open('fcts.txt') as methodsFile: 
    for methodName in methodsFile: 
    yahoo = Share('YHOO') 
    method = getattr(yahoo, methodName.strip()) 
    print (method()) 

但它看起來比較簡陋給我。

+1

儘管如此,你的'fcts.txt'應該包含像'get_open'和'get_change'這樣的行,沒有括號。如果文件中有括號,可以使用'methodName.strip('()\ n')'。 – Alfe

+0

感謝Alfe提供快速解決方案。完美的作品,我修改了fcts.txt,就像你提到的那樣。 – scounce

+0

:)歡迎來到StackOverflow!如果您認爲答案可以解決問題,請隨時接受答案(單擊答案左側的cckckmark)。 – Alfe