Foo.__new__ is what species of method?

Stefan Behnel stefan_ml at behnel.de
Tue Jul 14 08:26:46 CEST 2015


Steven D'Aprano schrieb am 14.07.2015 um 06:54:
> On Tuesday 14 July 2015 14:45, Ben Finney wrote:
>> The Python reference says of a class ‘__new__’ method::
>>
>>     object.__new__(cls[, ...])
>>
>>     Called to create a new instance of class cls. __new__() is a static
>>     method (special-cased so you need not declare it as such) that takes
>>     the class of which an instance was requested as its first argument.
> 
> This is correct. __new__ is a static method and you need to explicitly 
> provide the cls argument:

And it needs to be that way in order to allow superclass calls in a
subclass's __new__ method:

  class Super(object):
      def __new__(cls):
          return object.__new__(cls)

  class Sub(Super):
      def __new__(cls):
          return Super.__new__(cls)

If it was a classmethod, it would receive the class you call it on as first
argument (i.e. "Super" and "object" above), not the class you want to
instantiate (i.e. "Sub" or "Super").

Stefan




More information about the Python-list mailing list