Python 3的可选方案__

2024-10-05 14:28:44 发布

您现在位置:Python中文网/ 问答频道 /正文

在Python3中取消pickle时,是否有足够短的方法来调用类的__init__构造函数?通常的方法是使用__getinitargs__,如下所示

from __future__ import print_function
import pickle

class Car:

    def __init__(self, model, number):
        self.model = model
        self.number = number
        print("constructed with", model, number)
        # many other things to do

    def __getstate__(self):
        # intentionally returns None
        pass

    def __setstate__(self, state):
        pass

    def __getinitargs__(self):
        # save some information when pickling
        # (will be passed to the constructor upon unpickling)
        return self.model, self.number

c = Car("toyota", 1234)
d = pickle.loads(pickle.dumps(c))
print("reconstructed with", d.model, d.number)

但是,在新样式类和python3+中,__getinitargs__将被忽略,所有类只能是新样式类。存在__getnewargs__,但它只将参数传递给不同的__new__类方法。对上述示例的python2调用将导致

^{pr2}$

而python3调用会出错

>> constructed with toyota 1234
Traceback (most recent call last):
  File "test.py", line 26, in <module>
    print("reconstructed with", d.model, d.number)
AttributeError: 'Car' object has no attribute 'model'

忽略__getinitargs__方法。在

我不认为Python3会在这方面轻易倒退,所以希望我遗漏了一些显而易见的东西。在

用<{/cd2>代替问题{/cd2>不解决。在


Tags: to方法importselfnumbermodelinitdef
1条回答
网友
1楼 · 发布于 2024-10-05 14:28:44

如果您希望pickle通过调用Car(self.model, self.number)来取消对象的绑定,按照对Car的普通调用一样,通过__init__进行初始化,然后告诉它在^{} method中这样做:

def __reduce__(self):
    return (Car, (self.model, self.number))

Demo。在

相关问题 更多 >