__new__在正确类中未调用__init__
我有一个类叫做 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)
这个调用的表现是正常的,它通过调用 __new__()
和 __init__()
来创建 Vertex()
对象。
但是,当我对一个 Vertex()
对象进行反序列化(unpickle)时,__new__()
方法会被调用,但 __init__()
方法却没有被调用。我检查了一下,反序列化后这个实例的类是 Vertex
,所以据我所知 __init__()
应该是会被调用的。
1 个回答
2
在反序列化(也就是把存储的数据变回对象)时,故意不调用 __init__
方法。这意味着它会先创建一个新的“空”对象(通过 __new__
),然后再把之前的状态应用到这个新对象上。
你可以通过实现 __getinitargs__
(告诉反序列化工具无论如何都要调用 __init__
,并传入指定的参数)或者通过 __setstate__
来 自定义这个过程:
def __setstate__(self, state):
self.__dict__.update(state)
# do other things that need to be set on unpickling.