【发布时间】:2011-08-07 16:25:46
【问题描述】:
考虑以下代码:
class MyClass(object):
def __init__(self):
self.data_a = np.array(range(100))
self.data_b = np.array(range(100,200))
self.data_c = np.array(range(200,300))
def _method_i_do_not_have_access_to(self, data, window, func):
output = np.empty(np.size(data))
for i in xrange(0, len(data)-window+1):
output[i] = func(data[i:i+window])
output[-window+1:] = np.nan
return output
def apply_a(self):
a = self.data_a
def _my_func(val):
return sum(val)
return self._method_i_do_not_have_access_to(a, 5, _my_func)
my_class = MyClass()
print my_class.apply_a()
_method_i_do_not_have_access_to 方法接受一个 numpy 数组、一个窗口参数和一个用户定义的函数句柄,并返回一个数组,该数组包含函数句柄在输入数据数组的时间点上的 window 数据点上输出的值 -一种通用的滚动方法。我无权更改此方法。
如您所见,_method_i_do_not_have_access_to 将一个输入传递给函数句柄,该函数句柄是传递给_method_i_do_not_have_access_to 的数据数组。该函数句柄仅基于通过_method_i_do_not_have_access_to 传递给它的一个数据数组上的window 数据点计算输出。
除了通过_method_i_do_not_have_access_to 传递给_my_func 的数组之外,我需要做的是允许_my_func(传递给_method_i_do_not_have_access_to 的函数句柄)对data_b 和data_c 进行操作在相同的 window 索引中。 data_b 和 data_c 在 MyClass class 中全局定义。
我想到的唯一方法是在_my_func 中包含对data_b 和data_c 的引用,如下所示:
def _my_func(val):
b = self.data_b
c = self.data_c
# do some calculations
return sum(val)
但是,我需要在与val 相同的索引处对b 和c 进行切片(记住val 是通过_method_i_do_not_have_access_to 传递的数组的长度-window 切片)。
例如,如果_method_i_do_not_have_access_to 中的循环当前正在对输入数组的索引45 -> 50 进行操作,则_my_func 必须对b 和c 上的相同索引进行操作。
最终的结果是这样的:
def _my_func(val):
b = self.data_b # somehow identify which slide we are at
c = self.data_c # somehow identify which slide we are at
# if _method_i_do_not_have_access_to is currently
# operating on indexes 45->50, then the sum of
# val, b, and c should be the sum of the values at
# index 45->50 at each
return sum(val) * sum(b) + sum(c)
我有什么想法可以做到这一点吗?
【问题讨论】: