Python:pickle错误:__ new __()只需2个参数(给定1个)

时间:2015-06-14 12:11:03

标签: python pickle

相关:pickle load error "__init__() takes exactly 2 arguments (1 given)"

i < l.size()

输出:

import cPickle as pickle

pklfile = "test.pkl"

all_names = {}
class Name(object):
    def __new__(cls, c, s="", v=""):
        name = "%s %s %s" % (c, s, v)
        if all_names.has_key(name):
            return all_names[name]
        else:
            self = all_names[name] = object.__new__(cls)
            self.c, self.s, self.v = c, s, v

        return self

with open(pklfile, 'wb') as output:
    pickle.dump(Name("hi"), output, pickle.HIGHEST_PROTOCOL)

with open(pklfile, 'rb') as input:
    name_obj = pickle.load(input)

是否可以在不将第二个参数作为可选项的情况下完成此工作?

1 个答案:

答案 0 :(得分:5)

使用__getnewargs__,这是在对象被pickle时调用的,并提供了一个额外参数的元组,以便在取消渲染时传递给__new__

import cPickle as pickle

pklfile = "test.pkl"

all_names = {}
class Name(object):
    def __new__(cls, c, s="", v=""):
        name = "%s %s %s" % (c, s, v)
        if all_names.has_key(name):
            return all_names[name]
        else:
            self = all_names[name] = object.__new__(cls)
            self.c, self.s, self.v = c, s, v

        return self

    def __getnewargs__(self):
        return (Name.__repr__(self),)

    def __repr__(self):
        return '<Name %r, %r, %r>' % (self.c, self.s, self.v)

    def __str__(self):
        return "%s %s %s" % (self.c, self.s, self.v)

with open(pklfile, 'wb') as output:
    pickle.dump(Name("hi"), output, pickle.HIGHEST_PROTOCOL)

with open(pklfile, 'rb') as input:
    name_obj = pickle.load(input)
    print name_obj