Adding instance mthods

  • Thread starter Fernando Rodriguez
  • Start date
F

Fernando Rodriguez

Hi,

This sort of code works for staticmethods, but fails with instance methods.
Why does it fail? O:)

def g(x,y):
print 'static g', x, y
g = staticmethod(g)
return x+y
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'g',
'h']
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)
 
S

Sean Ross

Fernando Rodriguez said:
Hi,

This sort of code works for staticmethods, but fails with instance methods.
Why does it fail? O:)

def g(x,y):
print 'static g', x, y
g = staticmethod(g)
return x+y
['__class__', '__delattr__', '__dict__', '__doc__', '__getattribute__',
'__hash__', '__init__', '__module__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__setattr__', '__str__', '__weakref__', 'g',
'h']
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:
.... return x + y
....

If you want to have the same behaviour as a static method, use
staticmethod():
.... print "hello"
....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)
HTH
Sean
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,582
Members
45,065
Latest member
OrderGreenAcreCBD

Latest Threads

Top