我有一个这样定义的类:
class Client():
def __new__(cls):
print "NEW"
return cls
def __init__(self):
print "INIT"
当我使用它时,我得到以下输出:
cl = Client()
# INIT
__new__没有被调用。为什么?
我有一个这样定义的类:
class Client():
def __new__(cls):
print "NEW"
return cls
def __init__(self):
print "INIT"
当我使用它时,我得到以下输出:
cl = Client()
# INIT
__new__没有被调用。为什么?
类必须显式继承object才能__new__被调用。重新定义Client所以它看起来像:
class Client(object):
def __new__(cls):
print "NEW"
return cls
def __init__(self):
print "INIT"
__new__现在将在使用时调用:
cl = Client()
# NEW
请注意,__init__在这种情况下永远不会调用它,因为__new__它不会调用超类__new__作为它的返回值。
阅读了您的答案后,我对其进行了改进
class Client(object):
def __new__(cls):
print "NEW"
return super(Client, cls).__new__(cls)
def __init__(self):
print "INIT"
这样c = Client()输出
NEW
INIT
如预期。