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

Ned Batchelder ned at nedbatchelder.com
Mon Dec 12 20:12:32 EST 2016


On Monday, December 12, 2016 at 6:17:43 PM UTC-5, Ben Finney wrote:
> Ned Batchelder <ned at nedbatchelder.com> writes:
> 
> > Claiming that __init__ isn't a constructor seems overly pedantic to
> > me.
> 
> Whereas to me, claiming that ‘Foo.__init__’ is a constructor seems
> needlessly confusing.
> 
...
> * A constructor should return the instance. ‘Foo.__init__’ does not do
>   that; ‘Foo.__new__’ does.

This seems like an odd thing to insist on. C++ and Java constructors
don't return the instance.  C++ allocators return the instance. 
I'm happy to call __new__ an allocator. It serves exactly the same
role in Python as allocators do in C++: its job is to create the raw
material for the object, and they very rarely need to be written.

> 
> If the differences didn't matter I would agree that “overly pedantic” is
> fair. But those differences trip up newcomers. Thinking of
> ‘Foo.__init__’ leads people to wonder where the ‘self’ attribute came
> from – am I not meant to be constructing it? — and to attempt to return
> that instance.

Creating objects is confusing, but beginners don't come to Python
with an expectation of what a "constructor" is.  Filling in the 
attributes of an object is just as clearly a kind of construction
as allocating memory.

--Ned.


More information about the Python-list mailing list