[英]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.