Python constructors have particular semantics, and ‘Foo.__init__’ doesn't qualify (was: The right way to 'call' a class attribute inside the same class)
ben+python at benfinney.id.au
Mon Dec 12 18:57:09 EST 2016
Chris Angelico <rosuav at gmail.com> writes:
> On Tue, Dec 13, 2016 at 10:17 AM, Ben Finney <ben+python at benfinney.id.au> wrote:
> > 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. And when the time comes to lean about
> > ‘__new__’ the confusion continues, because the newcomer has been
> > told that something *else* is the constructor, so what's this?
> Ultimately, every language has slightly different semantics […], so
> you have to learn that the "constructor" might have slightly different
Please read again the message you extracted that quote from. I already
said I'm not claiming some other programming language's semantics should
What I'm saying is that in Python, there *already are* different
semantics for a constructor, and they don't match the semantics of
In Python, a constructor for a class is a class method. ‘Foo.__new__’ is
a constructor. ‘Foo.__init__’ is an instance method, so it's not a
In Python, a constructor for a class makes the instance where it didn't
already exist. ‘Foo.__new__’ is a constructor. ‘Foo.__init__’ requires
the instance to already be constructed, so it's not a constructor.
In Python, a constructor for a class returns a new instance of that
class. ‘Foo.__new__’ is a constructor. ‘Foo.__init__’ must return None,
so it's not a constructor.
In Python, a custom constructor for a class follows the above
descriptions. ‘datetime.fromtimestamp’ is a constructor.
‘datetime.__init__’ is not.
None of this argues from the semantics of other programming languages,
so telling me other languages have different semantics is not a response
to this argument.
I'm showing that Python classes *already have* constructors, and
‘Foo.__init__’ doesn't qualify because it doesn't have the semantics of
\ “I've always wanted to be somebody, but I see now that I should |
`\ have been more specific.” —Jane Wagner, via Lily Tomlin |
More information about the Python-list