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/ -- https://mail.python.org/mailman/listinfo/python-list