class Fabrica(object):
""" pra quê serve o metodo __new__ in python? """
def __new__(cls[, ...]):
# seu codigo aqui
#EOF
What does she do, and how do you make use of it?
class Fabrica(object):
""" pra quê serve o metodo __new__ in python? """
def __new__(cls[, ...]):
# seu codigo aqui
#EOF
What does she do, and how do you make use of it?
According to the definition 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. He is called first, and is responsible for returning a new instance of the 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 should not override __ new __ unless it is a subclass, an immutable type such as
str
,int
,unicode
ortuple
.
That is, you can use __new__
to have a control of the creation of the class instance and after it uses __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 like float
, str
or int
has an example that I took from the article Unifying Classes , a program that converts in. for metro:
class inch(float):
"Converte de polegadas para metros"
def __new__(cls, arg=0.0):
return (float.__new__(cls, arg*0.0254))
print(inch(12))
Output: 0.3048
But, this usage I found very interesting in the article, can really come in handy if you use 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__
? UnifyingTypesClasses , I highly advise you to read if you want to know more about it.