Adding instance mthods

Sean Ross sross at connectmail.carleton.ca
Fri Nov 7 09:47:49 EST 2003


"Fernando Rodriguez" <frr at easyjob.net> wrote in message
news:7k0nqvkvhfsvvvubfv7iag56l6i9n66eri at 4ax.com...
> Hi,
>
> This sort of code works for staticmethods, but fails with instance
methods.
> Why does it fail? O:-)
>
>
> >>> class C (object):
> def g(x,y):
> print 'static g', x, y
> g = staticmethod(g)
>
> >>> def h(self, x,y):
> return x+y
>
> >>> C.h = h
> >>> dir(C)
> ['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
> '__hash__', '__init__', '__module__', '__new__', '__reduce__',
> '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'g',
> 'h']
> >>> C.h(3,4)
>
> Traceback (most recent call last):
>   File "<pyshell#62>", line 1, in -toplevel-
>     C.h(3,4)
> TypeError: unbound method h() must be called with C instance as first
argument
> (got int instance instead)


Hi.
It fails because "C.h = h" adds an unbound instance method to C, not a
static method.
To use an unbound instance method, you either need to call it on an instance
of C
(e.g.,  c.h(x,y)) or pass an instance of C as the first parameter (e.g.,
C.h(c, x, y)).

For example:

>>> class C: pass
...
>>> def f(self, x, y):
...  return x + y
...
>>> C.f = f
>>> C.f
<unbound method C.f>
>>>
>>> c = C()
>>> c.f(2,3)
5
>>> C.f(c, 2,3)
5
>>>


If you want to have the same behaviour as a static method, use
staticmethod():

>>> def g():
...  print "hello"
...
>>> C.g = g
>>> C.g()
Traceback (most recent call last):
  File "<interactive input>", line 1, in ?
TypeError: unbound method g() must be called with C instance as first
argument (got nothing instead)
>>> C.g = staticmethod(g)
>>> C.g()
hello
>>>

HTH
Sean






More information about the Python-list mailing list