Why has __new__ been implemented as a static method?

Steven D'Aprano steve+comp.lang.python at pearwood.info
Sun May 4 10:16:00 EDT 2014


On Sun, 04 May 2014 20:03:35 +1200, Gregory Ewing wrote:

> Steven D'Aprano wrote:
>> If it were a class method, you would call it by MyBaseClass.__new__()
>> rather than explicitly providing the cls argument.
> 
> But that wouldn't be any good, because the base __new__ needs to receive
> the actual class being instantiated, not the class that the __new__
> method belongs to.


Which is exactly what method descriptors -- whether instance methods or 
class descriptors -- can do. Here's an example, using Python 2.7:

class MyDict(dict):
    @classmethod
    def fromkeys(cls, *args, **kwargs):
        print "Called from", cls
        return super(MyDict, cls).fromkeys(*args, **kwargs)

class AnotherDict(MyDict):
    pass


And in use:

py> MyDict.fromkeys('abc')
Called from <class '__main__.MyDict'>
{'a': None, 'c': None, 'b': None}
py> AnotherDict().fromkeys('xyz')
Called from <class '__main__.AnotherDict'>
{'y': None, 'x': None, 'z': None}


In both cases, MyDict's __new__ method receives the class doing the 
calling, not the class where the method is defined.

Whatever the difficulty is with __new__, it isn't something obvious.


-- 
Steven D'Aprano
http://import-that.dreamwidth.org/



More information about the Python-list mailing list