考虑下面的类,它继承自
datetime.time
:
class TimeWithAddSub(time):
_date_base = date(2000, 1, 1)
def __new__(cls, hour=0, minute=0, second=0, microsecond=0, tzinfo=None):
obj = super(TimeWithAddSub, cls).__new__(cls, hour, minute, second, microsecond, tzinfo)
obj._as_datetime = datetime(2000, 1, 1, hour, minute, second, microsecond, tzinfo=tzinfo)
return obj
尝试解封它会出现以下错误:
>>> t = TimeWithAddSub(10, 11, 12)
>>> b = pickle.dumps(t)
>>> b'\x80\x04\x95T\x00\x00\x00\x00\x....'
>>> t2 = pickle.loads(b)
>>> ... in __new__ ... TypeError: 'bytes' object cannot be interpreted as an integer
经过一番挖掘,似乎 unpickle 对象中的
__new__()
函数没有获得正确的参数:
hour
设置为 b'\x0b\x0c\r\x00\x00\x00'
minute=0, second=0, microsecond=0, tzinfo=None
)我尝试过覆盖
__reduce__()
,然后覆盖__getnewargs__()
,但这两种方法都会导致相同的错误。
有什么想法可以解决这个问题吗?
问题在于
datetime.time
实现了 __reduce_ex__()
,优先于 __reduce__()
。
一旦我实施了
TimeWithAddSub.__reduce_ex__()
,问题就解决了。