Bài viết phổ biến của tác giả
- c - 在位数组中找到第一个零
- linux - Unix 显示有关匹配两种模式之一的文件的信息
- 正则表达式替换多个文件
- linux - 隐藏来自 xtrace 的命令
假设我有一个 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)
câu trả lời hay nhất
tôi sẽ sử dụng super(B,self)
lấy B
的实例来调用 MỘT
的方法:
import cPickle
class A(object):
định nghĩa __init__(bản thân):
self.value=1
def __getstate__(self):
return self.value
def __setstate__(self, state):
self.value = state
class B(A):
định nghĩa __init__(bản thân):
super(B,self).__init__()
self.anothervalue=2
def __getstate__(self):
return (super(B,self).__getstate__(), self.anothervalue)
def __setstate__(self, state):
superstate, self.anothervalue = state
super(B,self).__setstate__(superstate)
b=B()
with open('a','w') as f:
cPickle.dump(b,f)
with open('a','r') as f:
c=cPickle.load(f)
print(b.value)
print(b.anothervalue)
参见 this article有关方法解析顺序 (MRO) 和 super 的更多信息。
关于python - 如果 pickle 父类和子类实例,如何在类层次结构中最好地 pickle/取消 pickle ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3554310/
Tôi là một lập trình viên xuất sắc, rất giỏi!