- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我在 python 2.7 上使用 pickle。我正在尝试调用我覆盖的两种方法 __getstate__
和 __getnewargs__
。我不能 pickle 属性 c
因为它是类 D
的一个实例。
nn = C(7, 2)
nn.d = 1
pickle.dump(nn, open('c_save.p', 'wb'))
nn2 = pickle.load(open('c_save.p', 'rb'))
print nn2.__dict__
返回:
getstate was called
setstate was called
{'a': 7, 'b': 2, 'd': 1}
我没有看到应该创建属性 c
的 __getnewargs__
调用。
我的代码:
import pickle
class D(object):
def __init__(self, i, j):
self.i = i
self.j = j
class C(object):
def __init__(self, a, b):
self.a = a
self.b = b
self.c = D(a, b)
self.d = 0
def __getstate__(self):
print 'getstate was called'
odict = self.__dict__.copy()
del odict['c']
return odict
def __getnewargs__(self):
print 'getnewargs was called'
return (self.b,self.a)
def __setstate__(self, dict):
print 'setstate was called'
self.__dict__.update(dict)
最佳答案
来自docs :
New-style types can provide a getnewargs() method that is used for protocol 2.
对于 pickle.dump
:
If the protocol parameter is omitted, protocol 0 is used.
因此,您必须像这样显式地将 pickle 协议(protocol)设置为 2:
pickle.dump(nn, open('c_save.p', 'wb'), protocol=2)
关于python - pickle : using both __getstate__ and __getnewargs__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43538628/
我在 python 2.7 上使用 pickle。我正在尝试调用我覆盖的两种方法 __getstate__ 和 __getnewargs__ 。我不能 pickle 属性 c 因为它是类 D 的一个实
据我所知,当在对象上调用 pickle.dumps 时,它会调用对象的 __getstate__ 方法(如果有的话)来确定要 pickle 的内容。 如果我创建一个类,例如: class Dict
我想问“如何 pickle 一个继承自 dict 并定义 __slots__ 的类”。然后我在 class B 中意识到了完全令人痛苦的解决方案下面实际上有效... import pickle cla
我不知道 __setstate__ 和 __getstate__ 方法是做什么的,所以帮我举个简单的例子。 最佳答案 这是一个非常简单的 Python 示例,它应该补充 pickle docs . c
我的问题是: class A(object): def __init__(self): #init def __setstate__(self,state):
出于某种原因,每次我尝试使用 easy_install 安装新模块时,都会出现错误: AttributeError: 'module' object has no attribute '__getst
我是一名优秀的程序员,十分优秀!