functions, classes, bound, unbound?

Steven Bethard steven.bethard at gmail.com
Sun Mar 25 06:20:36 CEST 2007


7stud wrote:
> Here is some example code that produces an error:
> 
> class Test(object):
>         def greet():
>                 print "Hello"
> 
> t = Test()
> t.greet()
> TypeError: greet() takes no arguments (1 given)
[snip]
> Test.greet()
> 
> TypeError: unbound method greet() must be called with Test instance as
> first argument (got nothing instead)

Methods in a class are generally expected to take an instance as their 
first argument, but your greet() method takes no arguments.  This is 
because classes don't invoke the function directly, they convert it to 
an 'unbound method' object::

     >>> class Test(object):
     ...     def greet():
     ...         print 'Hello'
     ...
     >>> Test.greet
     <unbound method Test.greet>
     >>> Test.greet()
     Traceback (most recent call last):
       File "<interactive input>", line 1, in <module>
     TypeError: unbound method greet() must be called with Test instance
     as first argument (got nothing instead)

If you really want to get to the original function, there are a couple 
of options.  You can go through the class's __dict__, or you can wrap 
your method with a @staticmethod decorator (which tells the class not to 
wrap the function when you try to use it)::

     >>> Test.__dict__['greet']
     <function greet at 0x00E708B0>
     >>> Test.__dict__['greet']()
     Hello
     >>> class Test(object):
     ...     @staticmethod
     ...     def greet():
     ...         print 'Hello'
     ...
     >>> Test.greet
     <function greet at 0x00E7D2F0>
     >>> Test.greet()
     Hello

STeVe



More information about the Python-list mailing list