Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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. Why?

like image 977
June Rhodes Avatar asked Sep 28 '12 10:09

June Rhodes


People also ask

What is __ New__ in Python?

In the base class object , the __new__ method is defined as a static method which requires to pass a parameter cls . cls represents the class that is needed to be instantiated, and the compiler automatically provides this parameter at the time of instantiation.

Can a class have an instance of itself python?

self : self represents the instance of the class. By using the "self" keyword all the attributes and methods of the python class can be accessed. __init__ : "__init__" is a reserved method in python classes. It is known as a constructor in object oriented concepts.


1 Answers

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.

like image 165
glglgl Avatar answered Nov 06 '22 09:11

glglgl