循环中的动态变量python

问题描述 投票:0回答:1

我在这里浏览了很多帖子来寻找解决方案,但也许我正在寻找错误的短语。我是 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()
...
python loops variables dynamic
1个回答
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())

但对我来说看起来相当粗糙。

© www.soinside.com 2019 - 2024. All rights reserved.