假设我有一个A类和一个从A派生的B类。我想挑选/取消类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)
答案 0 :(得分:4)
我会使用super(B,self)
来获取B
的实例来调用A
的方法:
import cPickle
class A(object):
def __init__(self):
self.value=1
def __getstate__(self):
return self.value
def __setstate__(self, state):
self.value = state
class B(A):
def __init__(self):
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)
有关方法解析顺序(MRO)和超级
的详细信息,请参阅this article