[Tutor] class methods as argument
Kent Johnson
kent37 at tds.net
Sat Feb 10 13:55:54 CET 2007
thomas coopman wrote:
> Hi,
>
> I want to do something like this, don't know how to properly explain it,
> so I just give you some example code
>
>>>> class Foo(object):
>>>> def method(self, arg):
>>>> print arg
>
>>>> def doSomething(object, func):
>>>> object.func("test")
>
>>>> object = Foo()
>>>> doSomething(object, Foo.method)
>
> I want to execute the class method given as argument,
> but this obvious doesn't work, but I don't know how to
> get it work,
First a quick note - don't use object as a parameter or variable name,
it will hide the definition of the built-in object class.
You are very close. Foo.method is called an 'unbound method' of class
Foo. The syntax for calling an unbound method is to pass a class
instance as the first argument, followed by the actual argument list. It
is actually the same argument list that you use when you declare the
function (starting with self).
So your example can be written this way:
In [4]: class Foo(object):
...: def method(self, arg):
...: print arg
In [6]: o=Foo()
In [8]: def doSomething(obj, func):
...: func(obj, "test")
In [9]: doSomething(o, Foo.method)
test
A more common way to do this is to use a 'bound method'. That is what
you get when you refer to instance.method instead of Class.method. A
bound method includes a reference to the particular instance and can be
called like an ordinary function. Rather than passing the instance and
the unbound method to doSomething(), just pass the bound method as a
single argument:
In [10]: def doSomething(func):
....: func("test")
In [12]: doSomething(o.method)
test
In summary:
Class.method => unbound method, call with instance as first arg
instance.method => bound method, call with normal argument list
Kent
More information about the Tutor
mailing list