Python's super() considered super!
Duncan Booth
duncan.booth at invalid.invalid
Fri May 27 11:05:21 EDT 2011
sturlamolden <sturlamolden at yahoo.no> wrote:
> On 26 Mai, 18:31, Raymond Hettinger <pyt... at rcn.com> wrote:
>> I just posted a tutorial and how-to guide for making effective use of
>> super().
>>
>> One of the reviewers, David Beazley, said, "Wow, that's really
>> great! I see this becoming the definitive post on the subject"
>>
>> The direct link is:
>>
>> http://rhettinger.wordpress.com/2011/05/26/super-considered-super/
>
> I really don't like the Python 2 syntax of super, as it violates
> the DRY principle: Why do I need to write super(type(self),self)
> when super() will do? Assuming that 'self' will always be named
> 'self' in my code, I tend to patch __builtins__.super like this:
>
> import sys
> def super():
> self = sys._getframe().f_back.f_locals['self']
> return __builtins__.super(type(self),self)
>
> This way the nice Python 3.x syntax can be used in Python 2.x.
>
>
Oh dear, you haven't thought this one through.
After your code above, try this:
>>> class A(object):
def foo(self):
print "A.foo"
>>> class B(A):
def foo(self):
print "B.foo"
super().foo()
>>> B().foo()
B.foo
A.foo
So far so good.
Now try this:
>>> class C(B): pass
>>> C().foo()
... infinite recursion follows ...
Oops. There's a reason why Python 2 requires you to be explicit about
the class; you simply cannot work it out automatically at run time.
Python 3 fixes this by working it out at compile time, but for Python 2
there is no way around it.
--
Duncan Booth http://kupuguy.blogspot.com
More information about the Python-list
mailing list