我怎样才能编写一个使这项工作的包装类?
def foo(a, b):
print a
data = np.empty(20, dtype=[('a', np.float32), ('b', np.float32)])
data = my_magic_ndarray_subclass(data)
foo(**data[0])
更多背景:
我有一对这样的函数,我想对其进行矢量化:
def start_the_work(some_arg):
some_calculation = ...
something_else = ...
cost = some_calculation * something_else
return cost, dict(
some_calculation=some_calculation,
some_other_calculation=some_other_calculation
)
def finish_the_work(some_arg, some_calculation, some_other_calculation):
...
start_the_work
用一堆不同的参数调用的意图,然后最低成本的项目就完成了。两个函数都使用了许多相同的计算,因此使用字典和 kwarg-splatting 来传递这些结果:
def run():
best, best_cost, continuation = min(
((some_arg,) + start_the_work(some_arg)
for some_arg in [1, 2, 3, 4]),
key=lambda t: t[1] # cost
)
return finish_the_work(best, **continuation)
我可以矢量化它们的一种方法如下:
def start_the_work(some_arg):
some_calculation = ...
something_else = ...
cost = some_calculation * something_else
continuation = np.empty(cost.shape, dtype=[
('some_calculation', np.float32),
('some_other_calculation', np.float32)
])
continuation['some_calculation'] = some_calculation
continuation['some_other_calculation'] = some_other_calculation
return cost, continuation
但尽管看起来像一本字典,continuation
但不能被夸夸其谈。