Reputation: 3307
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. Why?
Upvotes: 12
Views: 4928
Reputation: 91017
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
NEW
INIT
as intended.
Upvotes: 8
Reputation: 3307
Classes must inherit explicitly from object
in order for __new__
to be called. Redefine Client
so instead it looks like:
class Client(object):
def __new__(cls):
print "NEW"
return cls
def __init__(self):
print "INIT"
__new__
will now be called when used like:
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.
Upvotes: 7