我想避免在某個類的實例中酸洗某些字段。 目前,在酸洗前我只是將這些字段設置爲None,但我想知道是否有更優雅的解決方案?從Python中酸洗排除對象的字段
13
A
回答
5
有一個示例here可以解決您的問題__getstate__
和__setstate__
。
26
一個處理不屬於picklable對象實例屬性的方法是使用特殊的方法可用於修改類實例的狀態:,有getstate()和setstate這()。下面是一個例子
class Foo(object):
def __init__(self, value, filename):
self.value = value
self.logfile = file(filename, 'w')
def __getstate__(self):
"""Return state values to be pickled."""
f = self.logfile
return (self.value, f.name, f.tell())
def __setstate__(self, state):
"""Restore state from the unpickled state values."""
self.value, name, position = state
f = file(name, 'w')
f.seek(position)
self.logfile = f
當富的一個實例是醃製,Python將醃製當它調用該實例的,有getstate()方法只返回的值給它。同樣,在取消打開時,Python將提供未取消的值作爲實例的setstate()方法的參數。在setstate()方法中,我們可以根據我們挑選的名稱和位置信息重新創建文件對象,並將文件對象分配給實例的日誌文件屬性。
相關問題
- 1. 酸洗對象
- 2. 的Python酸洗
- 3. Python - 酸洗失敗numpy.void對象
- 4. Python酸洗字典EOFError
- 5. 從Python中的多個線程酸洗
- 6. 在Python中瞭解酸洗
- 7. Python中酸洗錯誤?
- 8. EOF Python中酸洗錯誤
- 9. 用importlib.util導入的酸洗對象
- 10. 酸洗互相引用的對象
- 11. Python的酸洗槽錯誤
- 12. 酸洗cv2.Knearest對象不工作
- 13. 完全Javascript對象的類似Python的酸洗
- 14. 如何避免酸洗字典VS酸洗列表的處罰
- 15. 酸洗的OrderedDict
- 16. 在Python中酸洗數據時的MemoryError
- 17. 酸洗AppEngine上
- 18. Python:酸洗模塊的替代品
- 19. 酸洗內部類
- 20. 酸洗類方法
- 21. python-3.x酸洗創建空文件
- 22. python multiprocessing shared Counter,酸洗錯誤
- 23. 使用會話時Python酸洗錯誤
- 24. GSON - 基於字段值排除對象
- 25. 從CSV中排除字段
- 26. Python酸洗錯誤:TypeError:對象pickle不返回列表。問題與numpy?
- 27. 試圖泡菜對象實例拋出酸洗錯誤
- 28. 酸洗數據問題
- 29. 酸洗一個類定義
- 30. 如何根據不同模型中的字段排除對象?
最快的手指第一:P – anijhaw 2010-02-27 02:15:20
固定鏈接:http://docs.python.org/2/library/pickle.html#example – WGH 2016-07-22 15:35:38