What is the __new__ in python method for?

Asked

Viewed 3,041 times

6

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

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

#EOF

What she makes, and how to make use of it?

  • There is a recent related question, the answer to which is also interesting here: http://answall.com/questions/109813/onde-fica-o-construct-da-classe-em-python

1 answer

9


According to the definition below:

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

The __new__ is the first step in creating an instance. It is called first, and is responsible for returning a new instance of the its class. In contrast, the __init__ returns nothing, he’s just responsible for initialization of the instance after the class is maid.

In general, you should not override the __new__ unless it is a subclass, an immutable guy like str, int, unicode or tuple.

That is, Voce can use the __new__ to have a control of the creation of the class instance and after it use the __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

The __new__ can be used with immutable class types as float, str or int there is an example I took from the article Unifying Types of 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))

print(inch(12))

Exit: 0.3048

But, this use I found very interesting in the article, really can come to be useful if you are using the standard Singleton, 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):
        pass

Sources:
Documentation.
Python’s use of __new__ and __init__?
Unifying , I strongly advise reading if you want to know more about.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.