[Python-ideas] Explicit self argument, implicit super argument
Neil Toronto
ntoronto at cs.byu.edu
Mon Nov 19 21:42:16 CET 2007
Guido van Rossum wrote:
> The reason for explicit self in method definition signatures is
> semantic consistency. If you write
>
> class C:
> def foo(self, x, y): ...
>
> This really *is* the same as writing
>
> class C:
> pass
>
> def foo(self, x, y): ...
> C.foo = foo
>
> And of course it works the other way as well: you really *can* invoke
> foo with an explicit argument for self as follows:
>
> class D(C):
> ...
>
> C.foo(D(), 1, 2)
>
> IOW it's not an implementation hack -- it is a semantic device.
Ah, thanks, that helps. (I'll be able to sleep tonight. :D) This
semantic device, of course, would really suck if applied to "super":
d = D()
C.foo(d, super(C, d), 1, 2) # strange and hideous
which is a great reason that the new "super" is implicit.
(Before I continue, please understand that I'm not arguing for a
language change. Responses to my last two ideas have shown me that I
need to thoroughly understand why things are as they are right now while
considering a change, and long before advocating one. It also goes over
better with the language designers.)
Now, correct me if I'm wrong, but it seems there are only two use cases
for DistantParentOfD.method(D_instance, ...):
1. The Good Case: you know the "next-method" as determined by the MRO
isn't the right one to call. Multiple inheritance can twist you into
this sort of behavior, though if it does, your design likely needs
reconsideration.
2. The Evil Case: you know the override method as defined by D isn't the
one you want for your extra-special D instance. This should be possible
but never encouraged.
Because the runtime enforces isinstance(D_instance, D), everything else
can be handled with D_instance.method(...) or self.method() or
super.method(). We know that #1 and #2 above are the uncommon cases,
which is why the new "super", which covers the common ones, doesn't
cover those.
Is it right to say that the explicit "self" parameter only exists to
enable those two uncommon cases?
Of course, if self were implicit, there would still need to be a way to
spell DistantParentOfD.method(D_instance, ...). Being the uncommon case,
maybe it shouldn't have a nice spelling:
as_parent(C, D_instance).method(...)
Trying-to-understandingly-yours,
Neil
More information about the Python-ideas
mailing list