【发布时间】:2021-03-18 06:43:33
【问题描述】:
from pathlib import Path
import pickle
class P(type(Path())):
def __init__(self, *args):
super().__init__()
self.a = ''
p = P()
p.a = 'x'
with open('xx', 'wb') as wf:
pickle.dump(p, wf)
p1 = pickle.load(open('xx', 'rb'))
print(p1.a) # here p1.a is ''
我正在创建pathlib.Path 的子类,并希望为其添加一些自定义属性。
问题是自定义属性在被pickle重新加载后会丢失。
如何解决这个问题。
我尝试过的其他解决方案:
- 使用
__slots__,同样的问题。 - 使用组合而不是继承,然后通过实现
__getattr__调度类似路径的方法。但是,在这种情况下,self.path未在pickle.load中初始化,从而导致__getattr__的无休止调用。
class File():
def __init__(self, *args):
self.path = Path(*args)
def __getattr__(self, item):
return getattr(self.path, item)
p = File('aaa')
p.exists() # no error
with open('xx', 'wb') as wf:
pickle.dump(p, wf)
p1 = pickle.load(open('xx', 'rb'))
# RecursionError: maximum recursion depth exceeded.
# This is due to call of self.path, in that moment, path is not in self.__dict__
【问题讨论】:
-
WHOOPs nvm,我搞错了
标签: python python-3.x inheritance serialization pickle