What is the __new__ method in python for?


class Fabrica(object):
    """ pra quê serve o metodo __new__ in python? """

    def __new__(cls[, ...]):
        # seu codigo aqui


What does it do, and how to make use of it?


As defined below:

Use __new__ when you need to control the creation of a new instance of the class. Use __init__ when you need to control the initialization of a new instance.

__new__ is the first step in creating an instance. It is called first, and is responsible for returning a new instance of your class. In contrast, __init__ does not return anything, it is only responsible for initializing the instance after the class is created.

In general, you shouldn't override __new__ unless it's a subclass, immutable type like str , int , unicode or tuple .

That is, you can use __new__ to control the creation of the instance of the class and then use __init__ to pass arguments, see an example:

class Fabrica(object):
    """ pra quê serve o metodo __new__ in python? """

    def __new__(cls[, ...]):
        # seu código aqui
        # definir uma rotina no momento da criação da instancia.
    def __init__(self, nome):
        # aqui ocorre a inicialização da instancia, 
        # pode iniciar os atributos da classe aqui.
        self.nome = nome

__new__ can be used with immutable class types like float , str or int is an example I took from Unifying Types Classes , a program that converts inches to meter:

class inch(float):
    "Converte de polegadas para metros"
    def __new__(cls, arg=0.0):
        return (float.__new__(cls, arg*0.0254))


Output: 0.3048

But, this use I found very interesting in the article, it can really come to be useful if you are going to use the singleton pattern, follow the example:

class Singleton(object):
    def __new__(cls, *args, **kwds):
        it = cls.__dict__.get("__it__")
        if it is not None:
            return it
        cls.__it__ = it = object.__new__(cls)
        it.init(*args, **kwds)
        return it
    def init(self, *args, **kwds):

Python's use of __new__ and __init__ ?
UnificandoTiposClasses , I highly recommend reading if you want to know more about it.

Scroll to Top