functions, classes, bound, unbound?

7stud bbxx789_05ss at yahoo.com
Sun Mar 25 08:13:53 CEST 2007


> ...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)
>

I think I found the rule in the GvF tutorial, which is essentially
what the error message says:
-------
When an unbound user-defined method object is called, the underlying
function (im_func) is called, with the restriction that the first
argument must be an instance of the proper class (im_class) or of a
derived class thereof.
--------

So, if you call a function using the syntax  TheClass.theMethod(),
then you are required to use an instance object as an argument.

In section 3.2 The Standard Class Hierarchy, it also says this:
-------
When a user-defined method object is created by retrieving a user-
defined function object from a class, its im_self attribute is None
and the method object is said to be unbound. When one is created by
retrieving a user-defined function object from a class via one of its
instances, its im_self attribute is the instance, and the method
object is said to be bound.
--------

In that first sentence, is he talking about retrieving the user-
defined function object from the class using the class name, e.g:

MyClass.someFunc

Is there some other way to retrieve a user-defined function object
from a class other than using the class name or an instance?


> If you really want to get to the original function, there are a couple
> of options.  

No.  Just trying to figure out how some things work.




More information about the Python-list mailing list