正确的类时__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)

其行为符合预期,并Vertex()通过同时调用__new__()__init__()

但是,当我解开一个方法时,将调用Vertex()__new__()方法,但不会调用该__init__()方法。我检查了一下,并且在取消选择该实例的类时Vertex,据我所知__init__()应该调用它。

马丁·彼得斯(Martijn Pieters)

__init__恢复对象时,不会故意进行去皮操作它创建一个新的“空”对象(带有__new__),然后将状态重新应用于该对象。

您可以通过实现以下任一方法来自定义此过程__getinitargs__:(告诉Pickle__init__ 无论如何都要使用给定的参数进行调用)或挂钩__setstate__

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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

python:运行__new__时出错?不调用__init__

如果定义了超类__new__,则不调用__init__子类

使用类的__new__方法作为工厂:__init__被调用两次

用户定义类型的元类的__new__和__init__在哪里被调用?

定义元类时,是否有任何理由选择__new__而不是__init__?

元类的__new__和__init__的参数

类和对象上的__new__和__init__

Python中的__new__和__init__

无法深度复制同时定义了__init__和__new__的类

动态添加元类为“ __init__”和“ __new__”的方法

如何在不调用__init__的情况下获取Python中的类引用

调用超类的__init__方法时发生TypeError

_replace不调用命名元组子类的__new__

子化namedtuple,__new__和__init__

Python(和Python C API):__new__与__init__

在__new__中更改arg不会继承__init__

在__init__调用中使用self.tr时,“从未调用%S的超类__init __()的RuntimeError”

有没有一种方法可以在不调用__init__的情况下实例化类?

为什么调用元类的__new__

Python 3内置类型__init__不调用super().__ init__?

断言__init__是用正确的参数调用的

当我从 D 类调用 C().__init__() 时,为什么 C().__init__() 的结果会打印两次?

用多重继承调用父类__init__,正确的方法是什么?

用多重继承调用父类__init__,正确的方法是什么?

禁止调用父类的 __init__()

在__init__内调用类函数

__init__不被双继承类调用

创建实例时默认调用__init__

从派生类自动调用基类 __init__