在co.Exec节点中使用python函数时,如何将自己的类作为参数传递



在添加像co.Exec(my_func, a=my_class)这样的Exec节点时,我试图将自己的用户定义类作为参数传递。然而,这似乎并不是开箱即用的。我可以编写任何序列化/反序列化函数来实现这一点吗?

您可以定义一个要序列化的to_str实例方法和一个要反串行化的from_str静态方法。

class my_class:
def __init__(self, val):
self.value = val
def to_str(self):
return repr(self.value)
@staticmethod
def from_str(val):
value = ast.literal_eval(val)
return MyClass(value)

这个eval/repr组合很简单,您可能想知道为什么它不使用JSON或pickle。此功能适用于复杂对象的数据库ID等情况,在这些情况下,对象太大或太复杂,无法完全序列化,但很容易从名称中重建。

一个更清晰的例子可能是金融工具的每日时间序列:

class time_series:
def __init__(self, name):
self.name = name
self.data = ... # Look up data in some data store
def to_str(self):
return self.name
@staticmethod
def from_str(value):
return time_series(value)

这可以用来编写非常自然的代码和命令行。举以下例子:

def plot(ts: time_series):
"Plot the given time series"
# Implementation omitted; it isn't really the interesting part
pass
if __name__ == "__main__":
co.main()

要绘制time_series,请正常传递此类,如:

aapl = time_series("AAPL.US")
plot(aapl)

要制作一个绘制它的节点,请将它传递给co.Exec:co.Exec(plot, aapl)

要从命令行绘图,调用python <file> plot --ts=AAPL.USco.main将反序列化名称"AAPL.US",并使用丰富的time_series对象调用plot()

最新更新