为什么不能在python中腌制对象的默认值?

时间:2017-06-20 19:40:15

标签: python object serialization pickle defaultdict

我有一个defaultdict(lambda : defaultdict(list))我要序列化然后反序列化。问题是我收到以下错误,我真的不知道该怎么做才能修复它。我使用的是python 2.7和ubuntu 16.04。

  

回溯(最近一次调用最后一次):文件" test_preprocessing.py",   51号线,在       pickle.dump(flights,f,protocol = pickle.HIGHEST_PROTOCOL)cPickle.PicklingError:不能pickle:属性   查找内置 .function失败

#!/usr/bin/env python

from collections import defaultdict
import cPickle as pickle

class Flight(object):
    def __init__(self, DDATE, WEEK_PERIOD, DPERIOD, RPERIOD, ALLIANCE, FARE):
            self.DDATE       = DDATE
            self.WEEK_PERIOD = WEEK_PERIOD
            self.DPERIOD     = DPERIOD
            self.RPERIOD     = RPERIOD
            self.ALLIANCE    = ALLIANCE
            self.FARE        = FARE

class Key(object):
    def __init__(self, DDATE, WEEK_PERIOD, DPERIOD, RPERIOD, ALLIANCE):
            self.DDATE       = DDATE
            self.WEEK_PERIOD = WEEK_PERIOD
            self.DPERIOD     = DPERIOD
            self.RPERIOD     = RPERIOD
            self.ALLIANCE    = ALLIANCE

    def __hash__(self):
        return hash((self.DDATE, self.WEEK_PERIOD, self.DPERIOD, self.RPERIOD, self.ALLIANCE))

    def __eq__(self, other):
        return (self.DDATE, self.WEEK_PERIOD, self.DPERIOD, self.RPERIOD, self.ALLIANCE) == (other.DDATE, other.WEEK_PERIOD, other.DPERIOD, other.RPERIOD, other.ALLIANCE)

    def __ne__(self, other):
        # Not strictly necessary, but to avoid having both x==y and x!=y
        # True at the same time
        return not(self == other)

if __name__ == "__main__":
    flight = Flight("", "","","", "", "")
    key    = Key("", "", "", "", "")
    flights = defaultdict(lambda : defaultdict(list))

    flights[key][20].append(flights)
    f = open('flights.pkl', 'wb')
    pickle.dump(flights, f, protocol=pickle.HIGHEST_PROTOCOL)
    f.close()

    f = open('flights.pkl', 'rb')
    flights = pickle.load(f)
    f.close()

0 个答案:

没有答案