如果父类和子类实例被腌制,如何在类层次结构中最好地腌制/取消腌制
假设我有一个类 A 和一个从 A 派生的类 B。我想 pickle/unpickle 类 B 的实例。A 和 B 都定义了 __getstate__/__setstate__ 方法(假设 A 和 B 很复杂,这使得需要使用 __getstate__ 和 __setstate__ )。 B应该如何调用A的__getstate__/__setstate__方法?我目前的但也许不是“正确”的方法:
class A(object):
def __init__():
self.value=1
def __getstate__(self):
return (self.value)
def __setstate__(self, state):
(self.value) = state
class B(A):
def __init__():
self.anothervalue=2
def __getstate__(self):
return (A.__getstate__(self), self.anothervalue)
def __setstate__(self, state):
superstate, self.anothervalue = state
A.__setstate__(self, superstate)
Assume I have a class A and a class B that is derived from A. I want to pickle/unpickle an instance of class B. Both A and B define the __getstate__/__setstate__ methods (Let's assume A and B are complex, which makes the use of __getstate__ and __setstate__ necessary). How should B call the __getstate__/__setstate__ methods of A? My current, but perhaps not the 'right' approach:
class A(object):
def __init__():
self.value=1
def __getstate__(self):
return (self.value)
def __setstate__(self, state):
(self.value) = state
class B(A):
def __init__():
self.anothervalue=2
def __getstate__(self):
return (A.__getstate__(self), self.anothervalue)
def __setstate__(self, state):
superstate, self.anothervalue = state
A.__setstate__(self, superstate)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我将使用
super(B,self)
获取B
的实例来调用A
的方法:请参阅 本文了解有关方法解析顺序 (MRO) 和 super 的更多信息。
I would use
super(B,self)
to get instances ofB
to call the methods ofA
:See this article for more info on method resolution order (MRO) and super.