【发布时间】:2018-03-20 09:15:21
【问题描述】:
如何修改下面的类以使它们可以选择?
这个问题:How to make a class which has __getattr__ properly pickable?类似,但是在getattr的使用中引用了错误的异常。
这个另一个问题似乎提供了有意义的见解Why does pickle.dumps call __getattr__?,但是它没有提供一个例子,老实说我无法理解我应该实现什么。
import pickle
class Foo(object):
def __init__(self, dct):
for key in dct:
setattr(self, key, dct[key])
class Bar(object):
def __init__(self, dct):
for key in dct:
setattr(self, key, dct[key])
def __getattr__(self, attr):
"""If attr is not in channel, look in timing_data
"""
return getattr(self.foo, attr)
if __name__=='__main__':
dct={'a':1,'b':2,'c':3}
foo=Foo(dct)
dct2={'d':1,'e':2,'f':3,'foo':foo}
bar=Bar(dct2)
pickle.dump(bar,open('test.pkl','w'))
bar=pickle.load(open('test.pkl','r'))
结果:
14 """If attr is not in channel, look in timing_data
15 """
---> 16 return getattr(self.foo, attr)
17
18 if __name__=='__main__':
RuntimeError: maximum recursion depth exceeded while calling a Python object
【问题讨论】:
标签: python python-2.7 pickle getattr