简体   繁体   English

为什么我的Python类没有调用__new__?

[英]Why is __new__ not being called on my Python class?

I have a class defined like so: 我有一个像这样定义的类:

class Client():
    def __new__(cls):
        print "NEW"
        return cls

    def __init__(self):
        print "INIT"

When I use it, I get the following output: 当我使用它时,我得到以下输出:

cl = Client()
# INIT

__new__ is not being called. __new__没有被调用。 Why? 为什么?

Having read your answer, I improve it with 读完答案之后,我就改进了

class Client(object):
    def __new__(cls):
        print "NEW"
        return super(Client, cls).__new__(cls)
    def __init__(self):
        print "INIT"

so that c = Client() outputs 这样c = Client()输出

NEW
INIT

as intended. 如预期。

Classes must inherit explicitly from object in order for __new__ to be called. 类必须从object显式继承才能调用__new__ Redefine Client so instead it looks like: 重新定义Client所以它看起来像:

class Client(object):
    def __new__(cls):
        print "NEW"
        return cls

    def __init__(self):
        print "INIT"

__new__ will now be called when used like: __new__现在将被调用,如下所示:

cl = Client()
# NEW

Note that __init__ will never be called in this situation, since __new__ does not invoke the superclass's __new__ as it's return value. 请注意,在这种情况下永远不会调用__init__ ,因为__new__不会调用超类的__new__作为返回值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM