这是我需要挑选的课程:
class sdict(dict):
def __getattr__(self, attr):
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
__reduce__ = dict.__reduce__
Run Code Online (Sandbox Code Playgroud)
在我看来__reduce__应该照顾酸洗,但相反:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
/home/daniyar/work/Apr24/<ipython-input-28-1cc94b920737> in <module>()
----> 1 pickle.dumps(sdict(a=1))
/usr/lib/python2.6/pickle.pyc in dumps(obj, protocol)
1364 def dumps(obj, protocol=None):
1365 file = StringIO()
-> 1366 Pickler(file, protocol).dump(obj)
1367 return file.getvalue()
1368
/usr/lib/python2.6/pickle.pyc in dump(self, obj)
222 if self.proto >= 2:
223 self.write(PROTO + chr(self.proto))
--> 224 self.save(obj)
225 self.write(STOP)
226
/usr/lib/python2.6/pickle.pyc in save(self, obj)
304 reduce = getattr(obj, "__reduce_ex__", None)
305 if reduce:
--> 306 rv = reduce(self.proto)
307 else:
308 reduce = getattr(obj, "__reduce__", None)
/usr/lib/python2.6/copy_reg.pyc in _reduce_ex(self, proto)
82 dict = None
83 else:
---> 84 dict = getstate()
85 if dict:
86 return _reconstructor, args, dict
TypeError: 'NoneType' object is not callable
ERROR: An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line statement', (171, 0))
Run Code Online (Sandbox Code Playgroud)
我__getstate__也应该定义吗?我完全失去了所有的这些多种方法,可用于自定义酸洗: __getinitargs__,__getstate__,__reduce__,等...
谷歌只向我提到我发现非常不清楚的官方泡菜文件.有人可以为我澄清这一点,还是指向一个好的泡菜教程?
我怀疑你是否走上了一条好路.
但是,要解决泡菜问题:
class sdict(dict):
def __getattr__(self, attr):
if attr.startswith('__'):
raise AttributeError
return self.get(attr, None)
__setattr__= dict.__setitem__
__delattr__= dict.__delitem__
Run Code Online (Sandbox Code Playgroud)
Pickle试图从你的对象获取状态,而dict没有实现它.你__getattr__正在被召唤"__getstate__"找到那个神奇的方法,然后返回None而不是AttributeError应该提升.如果你修好了__getattr__,泡菜就能正常工作.
事实上,为什么你还缺少缺少属性的无?这真的是你想让你的对象做的吗?
这是一个像你想要的那样伪装内置的难度的一个例子.封面下有微妙的东西,你必须参与其中.
PS:一个完全相同的问题.
| 归档时间: |
|
| 查看次数: |
1970 次 |
| 最近记录: |