正确的类时__new__不调用__init__ [英] __new__ not calling __init__ when correct class

查看:96
本文介绍了正确的类时__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__()

在另一个类的方法中,我得到了呼叫:

In the method of another class I have the call:

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__()

which behaves as expected, and creates the Vertex() by calling both __new__() and __init__()

但是,当我释放Vertex()的位置时,将调用__new__()方法,但不会调用__init__()方法.我检查了一下,然后取消实例的类是Vertex,据我所知应该调用__init__().

However, when I unpickle a Vertex() the __new__() method is called but not the __init__() method. I checked, and on unpickling the class of the instance is Vertex, so as far as I know __init__() should be called.

推荐答案

在恢复对象时,故意取消选择不会调用__init__.它将创建一个新的空"对象(带有__new__),然后将状态重新应用于该对象.

Unpickling deliberately does not call __init__ when reinstating an object. It creates a new 'empty' object (with __new__) then re-applies state to it.

您可以自定义此过程通过实现__getinitargs__(告诉Pickle使用给定的参数以任何方式调用__init__ )或挂接到__setstate__:

You can customize this process by implementing either __getinitargs__ (to tell Pickle to call __init__ anyway, with given arguments) or to hook into __setstate__:

def __setstate__(self, state):
    self.__dict__.update(state)
    # do other things that need to be set on unpickling.

这篇关于正确的类时__new__不调用__init__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆