[英]Error trying to pickle a user defined class
我刚刚开始使用 pickle,我正在尝试腌制我自己定义的 class,以便我可以在 Flask 应用程序中解开它。
这是我的 class 的代码:
class wma :
def __init__(self) : pass
def isConsistent(self, df, nConsecutive) :
sum = 0
for i in np.arange(1, nConsecutive + 1) :
sum += i
weights = []
for val in np.arange(1, nConsecutive + 1) :
weight = val / sum
weights.append(weight)
maxWMA = 0
for weight in weights :
maxWMA += weight
result = df[0].rolling(nConsecutive).apply(lambda x : np.sum(weights * x))
currentWMA = results.iloc[-1]
if currentWMA == maxWMA :
return True
else :
return False
这是我试图腌制它:
wma = wma()
file = open("wma", "wb")
pickle.dump(wma, file)
file.close()
但这给了我错误:
PicklingError: Can't pickle <class '__main__.wma'>: it's not the same object as __main__.wma
我是酸洗新手,所以我不确定出了什么问题。 有什么建议可以解决这个错误?
拥有一个 class 和一个具有相同名称的 class 的实例通常是一个坏主意,但特别是在这种情况下。 Pickling 依赖于全局 scope 中可用的类型名称,因此当它看到wma
是一个报告为wma
类型的变量时(该类型的名称不再存在,因为我们刚刚覆盖了它),它会感到困惑。
只需将变量命名为其他任何名称,就可以了。
my_wma = wma()
file = open("wma", "wb")
pickle.dump(my_wma, file)
file.close()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.