Where is the class constructor in Python?

4

Definition of Wikipedia.

  

The builder is a method   which is generally responsible for allocating the necessary resources to the   of the object beyond the initial definition of the variables of   status (attributes).

In Python the __init__ method is usually used to define attribute values, this is what I understand about this method, that is, in my point of view it is a constructor. See the example for the illustration:

class Carro(object):
    def __init__(self, modelo, ano): #Construtor da classe.
        self.modelo = modelo
        self.ano = ano

meuCarro = Carro("Jeep 4x4", 2015)

print("Modelo: %s" % meuCarro.modelo)
print("Ano: %d" % meuCarro.ano)

However, in the search I did, I discovered that the __init__ method is not the constructor of the class, but rather the method called when an object is required. Now I've been confused about where a constructor is from a class in Python. Where would the constructor location be?

    
asked by anonymous 23.01.2016 / 01:26

2 answers

4

What is a constructor

This is a technicality. We can consider it as the constructor. In fact, it is an initializer, as I had already written in previous question . But the initializer will be called every time a new object is created, shortly after calling the __new__ that will be the object's memory allocator. This allocator is provided by language if you do not define one, which is rarely needed, usually on immutable objects can be interesting.

And that's it. If you do a more in-depth search you will see that everyone, on a daily basis, will call the% of builder%. If I do not call it a constructor, then all languages I know are using the wrong name, because what they call constructor is also an initializer. They also usually call the allocator implicitly and usually do not need to define it in all classes. Of course, if it is to be thorough, the terminology is not quite the same.

__init__ is the destructor, right? Or is it just an "uninitializer", or just a despoiler? For all intents and purposes, it destroys the object. Is it the opposite of __del__ or the opposite of __new__ ? The documentation says he's a destructor. So one of the two is the constructor:).

The construction of the object in Python occurs in two steps, which is also true in several languages. It is not always apparent because allocation is rarely explored. In C ++, for example, you can override the __init__ operator to create a custom allocation. In C # or Java, it is not possible. But note that in these languages the constructor is just an initializer, and by chance it will always be called the allocator, which is fixed, before initializing the members, but the construct is the initialization. So we can say that the initializer is the constructor. Of course, it can never be called before calling the allocator.

Constructor expression

What you can do is create a constructor expression, which is a way of giving the consumer of that class a way to explicitly do all object building, and of course you should do the allocation and initialization somehow, even though calling the methods that already know how to do this. Which would not make sense if it were to do exactly the same thing. And of course you need to know what you're doing so you do not make mistakes. It's a way to give more flexibility to the building.

To create a form of the class doing other activities than allocation and initialization, you need to be able to do it call as a function . This is done by creating a new method. Then:

class A(object):
    def __init__(self):
        print("init")
    def __call__(self):
        print("call ")

a = A() #imprime init
A() #imprime call

If both have the same signature, __call__ will be called, unless you explicitly call __init__ , simplified: __call . A()() will always be called before.

Examples of using __init__ .

I would not call this a constructor.

Factory method

It is still possible to create a static method (without the __call__ ) that can be called to invoke the object construct, but I do not see this well. It does not seem idiomatic to me.

See running on ideone .

Additional reading

Python Object documentation is a good read to understand all this. An article that talks a lot about these magical methods .

    
23.01.2016 / 12:44
3

The method __init__ is the initializer of the class, so that the moment it is executed you already have the instance created ( self ), in python the class constructor method is __new__ :

class Foo:
    def __new__(cls):
        return cls()

Note that other than% w /% of method __init__ must return a value, in this case the instance of the class being created. See official documentation for more details.

An example of using the __new__ method is in creating singletons objects:

class Singleton:
    _instance = None

    def __new__(cls, *args, **kwargs):
        if not cls._instance:
            cls._instance = super().__new__(cls, *args, **kwargs)
        return cls._instance

However, in 99% of cases, you do not (and may not) need to change the constructor method of your class.

    
23.01.2016 / 11:38