我如何修改下面的类以使它们可以成像?
这个问题:如何使一个具有__getattr__正确可选择的类?类似但在使用getattr时引用了错误的异常.
这个问题似乎提供了有意义的见解为什么pickle.dumps会调用__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'))
Run Code Online (Sandbox Code Playgroud)
结果:
14 """If attr is not in channel, look in timing_data
15 """
---> 16 return getattr(self.foo, attr)
17
18 if …Run Code Online (Sandbox Code Playgroud) 首先我知道已经有很多关于这个特殊错误的问题,但我找不到任何解决它的确切背景的问题.我也尝试过为其他类似错误提供的解决方案,但没有任何区别.
我正在使用python模块pickle将对象保存到文件并使用以下代码重新加载它:
with open('test_file.pkl', 'wb') as a:
pickle.dump(object1, a, pickle.HIGHEST_PROTOCOL)
Run Code Online (Sandbox Code Playgroud)
这不会抛出任何错误,但是当我尝试使用以下代码打开文件时:
with open('test_file.pkl', 'rb') as a:
object2 = pickle.load(a)
Run Code Online (Sandbox Code Playgroud)
我收到此错误:
---------------------------------------------------------------------------
RecursionError Traceback (most recent call last)
<ipython-input-3-8c5a70d147f7> in <module>()
1 with open('2test_bolfi_results.pkl', 'rb') as a:
----> 2 results = pickle.load(a)
3
~/.local/lib/python3.5/site-packages/elfi/methods/results.py in __getattr__(self, item)
95 def __getattr__(self, item):
96 """Allow more convenient access to items under self.meta."""
---> 97 if item in self.meta.keys():
98 return self.meta[item]
99 else:
... last 1 frames repeated, from the frame …Run Code Online (Sandbox Code Playgroud)