我有一个班级Vertex()
使用以下方法:
def __new__(cls, pos_x, pos_y, size_x, size_y, text):
instance = super(Vertex, cls).__new__(cls)
#print 'variables {0}, {1}, {2}, {3}, {4}'.format(pos_x, pos_y, size_x, size_y, text)
#print instance.__class__.__name__
return instance
def __init__(self, pos_x=None, pos_y=None, size_x=None, size_y=None, text=None):
print 'init'
super(Vertex, self).__init__()
在另一堂课的方法中,我接到了电话:
self.vertices[touch.uid] = Vertex(pos_x=self.bounds[3][0], pos_y=self.bounds[2][1], size_x=self.bounds[1][0] - self.bounds[3][0], size_y= self.bounds[0][1] - self.bounds[2][1], text=None)
其行为符合预期,并通过同时调用Vertex()
和__new__()
来创建__init__()
但是,当我取消Vertex()
一个__new__()
方法时,会调用__init__()
方法而不是Vertex
方法。我查了一下,并且取消了实例的类是__init__()
,所以据我所知{{1}}应该被调用。
答案 0 :(得分:1)
在恢复对象时,故意不拣选__init__
。它会创建一个新的“空”对象(使用__new__
)然后重新应用状态。
您可__getinitargs__
实施__init__
(告诉Pickle无论如何使用给定的参数调用__setstate__
)或挂钩{{1} }:
def __setstate__(self, state):
self.__dict__.update(state)
# do other things that need to be set on unpickling.