我dict以一种简单的方式扩展为使用d.key符号而不是直接访问它的值d['key']:
class ddict(dict):
def __getattr__(self, item):
return self[item]
def __setattr__(self, key, value):
self[key] = value
Run Code Online (Sandbox Code Playgroud)
现在,当我尝试腌制它时,它会调用__getattr__find __getstate__,这既不存在也不必要。使用以下方法解压时也会发生同样的情况__setstate__:
>>> import pickle
>>> class ddict(dict):
... def __getattr__(self, item):
... return self[item]
... def __setattr__(self, key, value):
... self[key] = value
...
>>> pickle.dumps(ddict())
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 3, in __getattr__
KeyError: '__getstate__'
Run Code Online (Sandbox Code Playgroud)
我必须如何修改类ddict才能正确选择?
我想定义一个None用__getattr__方法返回未知属性的类。
这样做之后,我试图将该类的对象转储到 Pickle。
但是,我得到了错误
Traceback (most recent call last):
File "c:\SVN\Scripts\Rally\examples\t_pickle_None.py", line 14, in <module>
pickle.dump(toto, f, pickle.HIGHEST_PROTOCOL)
TypeError: 'NoneType' object is not callable
Run Code Online (Sandbox Code Playgroud)
没有定义__getattr__,它工作正常,但我想保留这个功能。
这是我的代码:如何使其工作__getattr__?
谢谢
import pickle
from typing import Any
class Toto:
def __init__(self, name:str) -> None:
self.name = name
def __getattr__(self, _: str) -> Any:
"""Return None for all unknown attributes"""
return None
toto = Toto("Toto")
with open('toto.pkl', 'wb') as f:
pickle.dump(toto, f, pickle.HIGHEST_PROTOCOL)
Run Code Online (Sandbox Code Playgroud)