The right way to 'call' a class attribute inside the same class
juan0christian at gmail.com
Mon Dec 12 17:08:42 EST 2016
On Mon, Dec 12, 2016 at 6:59 PM, Thomas 'PointedEars' Lahn
<PointedEars at web.de> wrote:
Using the Python official doc link you provided, it clearly states
that `__new__` is the one called to "create a new instance of class
[...] The return value of __new__() should be the new object instance
(usually an instance of cls)." On the other hand, `__init__` is
"called after the instance has been created (by __new__()), but before
it is returned to the caller."
Here we have the same mindset regarding `__new__` vs `__init__`:
"Note: __init__ is sometimes called the object’s constructor, because
it is used similarly to the way that constructors are used in other
languages, but that is not technically correct – it’s better to call
it the initialiser. There is a different method called __new__ which
is more analogous to a constructor, but it is hardly ever used."
"We want to define the attributes of an instance right after its
creation. __init__ is a method which is immediately and automatically
called after an instance has been created. [...] The __init__ method
is used to initialize an instance."
"In Python, constructors are defined by one or both of __new__ and
__init__ methods. A new instance is created by calling the class as if
it were a function, which calls the __new__ and __init__ methods. If a
constructor method is not defined in the class, the next one found in
the class's Method Resolution Order will be called."
"The __init__() method is called immediately after an instance of the
class is created. It would be tempting — but technically incorrect —
to call this the “constructor” of the class. It’s tempting, because it
looks like a C++ constructor (by convention, the __init__() method is
the first method defined for the class), acts like one (it’s the first
piece of code executed in a newly created instance of the class), and
even sounds like one. Incorrect, because the object has already been
constructed by the time the __init__() method is called, and you
already have a valid reference to the new instance of the class."
In general, the idea is simple, `__new__` constructs and `__init__`
initializes, this is what I believe in, after all the name `__init__`
already tell us that it's a *init* ialiser...
More information about the Python-list