我正在使用pickle将我的类转储到一个文件,如下所示,但是在打印加载对象的属性时我得到了AttributeError
。
import cPickle as pickle
from requests.sessions import Session
class B(Session):
def __init__(self, b):
super(B, self).__init__()
self.b = b
if __name__ == '__main__':
b = B(2,)
with open('/tmp/b.pl', 'wb') as f:
pickle.dump(b, f)
with open('/tmp/b.pl', 'rb') as f:
t = pickle.load(f)
print t.headers
print t.b # AttributeError
无论如何,我找到了如何解决这个问题,只需定义B
,如下所示:
class B(Session):
__attrs__ = [
'headers', 'cookies', 'auth', 'proxies', 'hooks', 'params', 'verify',
'cert', 'prefetch', 'adapters', 'stream', 'trust_env',
'max_redirects', 'b'
]
def __init__(self, b):
super(B, self).__init__()
self.b = b
那时没关系。似乎原因是__attrs__
,然后我试着测试一下:
class A(object):
__attrs__ = []
def __init__(self, a):
self.a = a
class C(A):
def __init__(self, a, c):
super(C, self).__init__(a)
self.c = c
if __name__ == '__main__':
b = B(2,)
c = C(1, 2)
with open('/tmp/c.pl', 'wb') as f:
pickle.dump(c, f)
with open('/tmp/c.pl', 'rb') as f:
t = pickle.load(f)
print t.a
print t.c
但是,我没有错误,为什么会这样?