Why has __new__ been implemented as a static method?
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat May 3 23:37:21 EDT 2014
On Sun, 04 May 2014 11:21:53 +1200, Gregory Ewing wrote:
> Steven D'Aprano wrote:
>> I'm not entirely sure what he means by "upcalls", but I believe it
>> means to call the method further up (that is, closer to the base) of
>> the inheritance tree.
>
> I think it means this:
>
> def __new__(cls):
> MyBaseClass.__new__(cls)
>
> which wouldn't work with a class method, because MyBaseClass.__new__
> would give a *bound* method rather than an unbound one.
If it were a class method, you would call it by MyBaseClass.__new__()
rather than explicitly providing the cls argument.
> Python 3's version of super() seems to work with class methods, but
> Python 2's doesn't (or at least I couldn't get it to work in a brief
> test).
Works for me. Perhaps you got your super() call wrong?
py> class MyDict(dict):
... @classmethod
... def fromkeys(cls, *args, **kwargs):
... print "Calling overridden method."
... return super(MyDict, cls).fromkeys(*args, **kwargs)
...
py> MyDict.fromkeys('abc')
Calling overridden method.
{'a': None, 'c': None, 'b': None}
py> MyDict().fromkeys('abc')
Calling overridden method.
{'a': None, 'c': None, 'b': None}
> Also, I don't think super() existed at all when __new__ was
> invented.
Well, I don't know about that, but super was introduced in the same
version as new-style classes with __new__.
--
Steven D'Aprano
http://import-that.dreamwidth.org/
More information about the Python-list
mailing list