Why is __new__ not being called in my Python class?

I have a class defined like this:

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__ not called. Why?

+7
source share
2 answers

After reading your answer, I will improve it with

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

for c = Client() output

 NEW INIT 

as expected.

+6
source

Classes must explicitly inherit from object to call __new__ . Override Client , so it looks like this:

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

__new__ will now be called when used as:

 cl = Client() # NEW 

Note that __init__ will never be called in this situation, since __new__ does not call the __new__ superclass as the return value.

+3
source

All Articles