您可以使用 setattr() 将变量添加到类中,但您需要一个类来保存变量:
class DataReader:
def __init__(self, ticker, something, start, stop):
self.ticker = ticker
self.something = something
self.start = start
self.stop = stop
class test:
def __init__(self, tickers):
for t in tickers:
setattr(self, t, DataReader(t, 'stooq', 1, 1))
new = test(['BAC','C','GS','JPM','MS','WFC'])
测试:
print(new.BAC)
<__main__.DataReader object at 0x0000017847C10128>
然而,更好的方法是将对象保存在字典中:
tickers = {t: DataReader(t, 'stooq', 1, 1) for t in ['BAC','C','GS','JPM','MS','WFC']}
输出:
{'BAC': <__main__.DataReader at 0x17847d6af28>,
'C': <__main__.DataReader at 0x17847d6ac18>,
'GS': <__main__.DataReader at 0x17847d6af60>,
'JPM': <__main__.DataReader at 0x17847d6afd0>,
'MS': <__main__.DataReader at 0x17847d6a7f0>,
'WFC': <__main__.DataReader at 0x17847d6a828>}