简体   繁体   English

尝试腌制用户定义的 class 时出错

[英]Error trying to pickle a user defined class

I've just started to use pickle, and I'm trying to pickle a class I defined on my own so that I can unpickle it in a Flask App.我刚刚开始使用 pickle,我正在尝试腌制我自己定义的 class,以便我可以在 Flask 应用程序中解开它。

This is the code for my class:这是我的 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

And here's me trying to pickle it:这是我试图腌制它:

wma = wma()
file = open("wma", "wb")
pickle.dump(wma, file)
file.close()

But this gives me the error:但这给了我错误:

PicklingError: Can't pickle <class '__main__.wma'>: it's not the same object as __main__.wma

I'm new to pickling so I'm not sure what's wrong.我是酸洗新手,所以我不确定出了什么问题。 Any suggestions to resolve the error?有什么建议可以解决这个错误?

Having a class and an instance of that class with the same name is a bad idea in general, but specifically in this case.拥有一个 class 和一个具有相同名称的 class 的实例通常是一个坏主意,但特别是在这种情况下。 Pickling depends on type names being available in the global scope, so when it sees that wma is a variable reporting to be of type wma (a type whose name no longer exists since we just overwrote it), it gets confused. Pickling 依赖于全局 scope 中可用的类型名称,因此当它看到wma是一个报告为wma类型的变量时(该类型的名称不再存在,因为我们刚刚覆盖了它),它会感到困惑。

Just name the variable anything else and you'll be fine.只需将变量命名为其他任何名称,就可以了。

my_wma = wma()
file = open("wma", "wb")
pickle.dump(my_wma, file)
file.close()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM