Multiple inheritance, super() and changing signature
steve at pearwood.info
Fri Jun 3 08:47:13 EDT 2016
On Fri, 3 Jun 2016 07:18 am, Random832 wrote:
> On Thu, Jun 2, 2016, at 13:36, Steven D'Aprano wrote:
>> But since the constructor/initialiser methods are so closely linked, many
>> people are satisfied to speak loosely and refer to "the constructor" as
>> either, unless they specifically wish to distinguish between __new__ and
> Where there is looseness, it comes from the fact that because __init__
> is always called even if __new__ returns a pre-existing object
That's not quite correct. __init__ is not always called:
If __new__() does not return an instance of cls, then the new
instance’s __init__() method will not be invoked.
> often place code in __new__ which mutates the object to be returned,
> acting somewhat like a traditional constructor by assigning attributes
> But it is __init__ that acts like the thing that is called a constructor
> in many languages, and no-one's produced a single example of a language
> which uses "constructor" for something which allocates memory.
Yes you have: Python. Like it or not, it is common usage to call __new__ the
constructor and __init__ the initialiser. Even if the official docs are
agnostic on the issue, it is still widespread (but not universal) in the
I have only come across two languages that split the "constructor" into two
methods, Objective C and Python. That does make Python rather special
compared to most other OO languages.
Objective C calls the part that allocates memory "alloc" (and is presumably
known as "the allocator") and the part which initialises it "init". "init"
is explicitly and officially known as the initialiser. Here's that link
again in case you missed it.
Even if you dismiss Python, you can't dispute that the official Apple docs
for Cocoa refer to initialiser rather than constructor.
Python also follows that pattern of splitting the "constructor" into two:
__new__ and __init__. Until Python 2.2 introduced new-style classes, it was
common to refer to __init__ as the constructor. For instance, I have the
Python Pocket Reference from Python 1.5 which describes __init__ as:
Constructor: initialize the new instance, self.
When object and new-style classes were introduced, people wanted to
distinguish them. Since __new__ constructs the object, and __init__
initialises it (even in old-style classes __init__ is said to *initialise*
the instance), it seems natural to call __new__ the constructor and
__init__ the initialiser.
Perhaps we ought to have called them the allocator and the initialiser. If
you want to lead the push for that terminology, please be my guest.
More information about the Python-list