[Python-ideas] Explicit self argument, implicit super argument
Guido van Rossum
guido at python.org
Mon Nov 19 20:11:21 CET 2007
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.
--Guido
On Nov 19, 2007 11:00 AM, Neil Toronto <ntoronto at cs.byu.edu> wrote:
> (Disclaimer: I have no issue with "self." and "super." attribute access,
> which is what most people think of when they think "implicit self".)
>
> While showing a coworker a bytecode hack I made this weekend - it allows
> insertion of arbitrary function parameters into an already-existing
> function - he asked for a use case. I gave him this:
>
> class A(object):
> # ...
> def method(x, y):
> self.x = x
> super.method(y)
>
>
> where 'method' is replaced by this method wrapper via metaclass or
> decorator:
>
> def method_wrapper(self, *args, **kwargs):
> return hacked_method(self, super(cls, self), *args, **kwargs)
>
>
> These hackish details aren't important, the resulting "A.method" is.
>
> It occurred to me that explicit self and implicit super is semantically
> inconsistent. Here's Python 3000's version of the above (please compare):
>
> class A(object):
> def method(self, x, y):
> self.x = x
> super.method(y)
>
>
> Why have a magic "super" local but not a magic "self" local? From a
> *general usage* standpoint, the only reason I can think of (which is not
> necessarily the only one, which is why I'm asking) is that a person
> might want to change the name of "self", like so:
>
> class AddLike(object):
> # ...
> def __add__(a, b):
> # return something
> def __radd__(b, a):
> # return something
>
>
> But reverse binary special methods are the only case where it's not
> extremely bad form. Okay, two reasons for explicit self: backward
> compatibility, but 2to3 would make it a non-issue.
>
> From an *implementation standpoint*, making self implicit - a cell
> variable like super, for example - would wreak havoc with the current
> bound/unbound method distinction, but I'm not so sure that's a bad thing.
>
> Neil
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
--
--Guido van Rossum (home page: http://www.python.org/~guido/)
More information about the Python-ideas
mailing list