Method binding confusion

David MacQuigg dmq at gain.com
Tue May 25 07:36:01 EDT 2004


On Mon, 24 May 2004 17:21:07 -0700, Josiah Carlson <jcarlson at uci.edu>
wrote:

>It can be done.
>
> >>> import math
> >>>
> >>> def mypow(x, y):
>...       return x**y
>...
> >>> class MathA:
>...    pow = math.pow
>...
> >>> class MathB:
>...    pow = staticmethod(mypow) <== ***
>...
> >>> ma = MathA()
> >>> mb = MathB()
> >>>
> >>> ma.pow(2,4)
>16.0
> >>> mb.pow(2,4)
>16

Yes.  This is the solution I came up with.  It's a valuable exercise
for students, but I warn them not to worry about what's going on in
Python, just look at the error message and see if you can fix the
problem.  The error message is the familiar:

TypeError: mypow() takes exactly 2 arguments (3 given)

This message, and the knowledge that calling from an instance adds an
extra argument, should be sufficient clue to add the staticmethod
wrapper.

-- Dave




More information about the Python-list mailing list