[Tutor] question: how do you pass a function as argument for application?

Daniel Yoo dyoo@hkn.EECS.Berkeley.EDU
Thu, 21 Sep 2000 21:26:39 -0700 (PDT)


On Wed, 20 Sep 2000, WIGETMAN Robert wrote:

> thanks for the help, your suggestion works, but how do I do it in a class
> instance method?
> 
> class C:
> 	def __init__(self,x):
> 		self.val = x
> 	def foo(self):
> 		print self.val
> 	def doit(self, func):
> 		self.func()  # this is where I can't get it to work??
> 
> >>> x = C(1)
> >>> x.foo()
> 1
> >>> x.doit(x.g)


Tricky!  What's happening is that x.doit is a "bound" method to your 'x'
instance:

###
>>> x = C(1)
>>> x.doit
<method C.doit of C instance at 8101e60>
###

This is in contrast to an "unbound method" from the C class:

###
>>> C.doit
<unbound method C.doit>
###

When you make an instance of a class, its methods gets bound into with
self.  This example might make things clearer:

###
>>> myfunc = x.doit
>>> myfunc()
Traceback (innermost last):
  File "<stdin>", line 1, in ?
TypeError: not enough arguments; expected 2, got 1
###

Where did the first argument come from?  What's happening is a little
"behind-the-scenes" action --- since we pulled the bound doit() method
from x, the self argument will implicitly be attached as the first
argument.


*some time later*

I have to end this message abruptly --- I won't be able to check Python
stuff for a while because of a slight time constraint.  Sorry!  Hopefully
another tutor can help explain how to get your code working.