我试图使用函数调用相同类型的类列表的函数。我想要这个,因为我必须遍历几个对象并对它们执行相同的操作,并且我有几个不同的函数运行这样的for
循环。
鉴于此:
def make_timeSeries(symbol):
return pandas.DataFrame(symbol) # Pseudo-code; But the return value is a pd.DataFrame Object nonetheless.
Class TimeSeries:
def __init__(self, symbol):
self.series = make_timeSeries(symbol)
def get_y_of_day(self, day, _type):
# Returns a y value for a given X (date) value from a timeline.
if isinstance(day, str):
day = funcs.convert_str_to_datetime(day)
return self.series[(self.series['Date'] >= day) &
(self.series['Type'] ==
_type)].head(1)['Value'].values[0]
Class Market:
def __init__(self, symbols):
self.instruments = {}
for symbol in symbols:
self.instruments[symbol] = TimeSeries(make_timeSeries(symbol))
def _market_day_apply_funcs(self, func, func_list=None, *args):
# calls a given class function of TimeSeries for each TimeSeries stored in self.instruments
ys = []
for symbol in self.instruments:
ys.append(self.instruments[symbol].func(args))
if func_list is None:
return ys
else:
return func_list(ys)
def market_ys_of_day(self, day, _type):
# Masking function, returns a list of all instruments at the given X (Date) value.
return self._market_day_apply_funcs(get_y_of_day, day, _type)
我按照以下方式调用它:
print(market.market_ys_of_day('2016-2-1', 'vola'))
然而,这会引发NameError
:
Traceback (most recent call last):
File "/markets.py", line 73, in <module>
print(market.market_ys_of_day('2016-2-1', 'vola'))
File "/markets.py", line 38, in market_ys_of_day
return self._market_day_apply_funcs(get_y_of_day, day, _type)
NameError: name 'get_y_of_day' is not defined
我假设解决此错误的方法是传递整个self.instruments[symbol].func
,但这会破坏函数本身的目的,即没有重复{{1}在每个for
函数中循环。
任何人都知道这方面的解决方案吗?
修改
可能有意义的是声明我的IDe突出显示market_day_*
参数未在函数范围中使用。如果有人能够解释这一点,还有额外的功劳。
答案 0 :(得分:1)
据我所见:
ys.append(self.instruments[symbol].func(args))
应该是:
ys.append(func(args))
和
return self._market_day_apply_funcs(get_y_of_day, day, _type)
应该是:
return self._market_day_apply_funcs(TimeSeries.get_y_of_day, day, _type)