Is this the proper way to use a class method?

Chris Rebert clp2 at rebertia.com
Fri Mar 2 03:08:17 EST 2012


On Thu, Mar 1, 2012 at 11:16 PM, John Salerno <johnjsal at gmail.com> wrote:
>> That's just a coincidence. Your supercall is ought to be: super().move()
>> In contrast, super().move(self) calls the superclass instance method
>> `move` with 2 arguments, both `self`, which just happens to work given
>> your move() method, inside which `cls` isn't actually a class like it
>> ought to be.
>
> Thank you! This is the whole reason I tried using a class method in the first place. I was getting an error that said my move method only takes one argument, but I was passing in two.
>
> But if I make the super call as super().move(), how does that work? The move method in the superclass takes an argument, and if I just do super().move(), isn't it the subclass that's getting passed to it?

The instance of the subclass (i.e. what Pawn.move() considers `self`)
gets passed to it.

> How does the superclass move method know what 'self' is if it doesn't get passed to it as I did originally?

Oh, but it does get passed, just implicitly. `super()` basically grabs
`self` magically from its caller, and uses it to bind method calls on
the magical object returned by `super()`.

`super().move()` ends up being, in this particular case, equivalent to:
    ChessPiece.move(self)
which is incidentally how one would write this without using super().

Here is a useful[1] "identity" to ponder:
    x.y(z) === type(x).y(x, z)

Cheers,
Chris
--
[1]: In the sense of a useful lie[2]; it's far from completely
accurate; it (at the least) ignores metaclasses, overridings of
__getattribute__(), and a third thing that's difficult to clearly put
into words.
[2]: http://c2.com/cgi/wiki?UsefulLie [3]
[3]: Yes, my footnotes have footnotes.
http://rebertia.com



More information about the Python-list mailing list