简体   繁体   中英

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.

This is the code for my 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. 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.

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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