Adding instance mthods

Fernando Rodriguez frr at
Fri Nov 7 15:07:28 CET 2003


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',
>>> C.h(3,4)

Traceback (most recent call last):
  File "<pyshell#62>", line 1, in -toplevel-
TypeError: unbound method h() must be called with C instance as first argument
(got int instance instead)

More information about the Python-list mailing list