循环中的动态变量python

时间:2017-03-07 11:17:33

标签: python loops variables dynamic

我在这里查看了许多帖子以寻求解决方案,但也许我正在寻找错误的短语。我是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()
...

谢谢你, 斯蒂芬

1 个答案:

答案 0 :(得分: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())

但它看起来相当粗糙。