The right way to 'call' a class attribute inside the same class

Steve D'Aprano steve+python at pearwood.info
Mon Dec 12 17:16:12 EST 2016


On Tue, 13 Dec 2016 07:15 am, Ned Batchelder wrote:

> Claiming that __init__ isn't a constructor seems overly pedantic to me.
> What's true is that Python's constructors (__init__) are different than
> C++ constructors.  In C++, you don't have an object of type T until the
> constructor has finished. In Python, you have an object of type T before
> __init__ has been entered.
> 
> The reason to call __init__ a constructor is because of what is the same
> between C++ and Python: the constructor is where the author of the class
> can initialize instances of the class.

That logic would have been more convincing back in the days of classic
classes in Python 1.5 or 2.0, less so after class/type unification where we
have an actual constructor __new__ that creates the instance.

The section of the docs that deal with object customization takes an
agnostic position, referring only to the "class constructor EXPRESSION"
(i.e. MyClass(spam, eggs) or equivalent):

https://docs.python.org/2/reference/datamodel.html#object.__init__

and similarly in __new__ (this time the v3 docs, just because):

https://docs.python.org/3/reference/datamodel.html#object.__new__


so if you want to be pedantic, one might argue that Python has a concept
of "object/class constructor expressions", MyClass(spam, eggs), but not of
constructor method(s). But that seems even stranger than insisting that:

- __new__ is the constructor method;
- __init__ is the initializer method.


Another way of naming things is to say that:

- __new__ is the allocator;
- __init__ is the initializer;
- the two together, __new__ + __init__, make up the constructor.

Not to be confused with the constructor expression, MyClass(spam, eggs), or
the alternative constructor, MyClass.make_instance(...).

Naming things is hard.



-- 
Steve
“Cheer up,” they said, “things could be worse.” So I cheered up, and sure
enough, things got worse.




More information about the Python-list mailing list