Mock / MagicMock没有默认的__name__
属性,我是手动添加的。
运行以下代码段时:
import pickle
from mock import MagicMock
m = MagicMock()
m.__name__ = 'my name'
m.__reduce__ = lambda self: (MagicMock, ())
print(m.__name__)
b = pickle.dumps(m)
pickled_m = pickle.loads(b)
print(pickled_m.__name__)
我遇到错误:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/.../.pyenv/virtualenv/lib/python3.6/site-packages/mock/mock.py", line 716, in __getattr__
raise AttributeError("Mock object has no attribute %r" % name)
AttributeError: Mock object has no attribute '__name__'
如何指示泡菜序列化__name__
属性?
答案 0 :(得分:0)
您的问题与pickle
无关,您的MagicMock
类具有__getattr__
魔术方法的自定义实现,在某些情况下会引发AttributeError
异常。为了证明这一点,请使用以下代码:
import pickle
class A():
a = 10
a = A()
a.__name__ = "A"
ap = pickle.dumps(a)
na = pickle.loads(ap)
print(na.__name__)
将输出:
'A'
因此__name__
的酸洗和酸洗没有问题。