在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调用将导致
而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>不解决。在
如果您希望} method 中这样做:
pickle
通过调用Car(self.model, self.number)
来取消对象的绑定,按照对Car
的普通调用一样,通过__init__
进行初始化,然后告诉它在^{Demo。在
相关问题 更多 >
编程相关推荐