[Tutor] class methods as argument

thomas coopman thomas.coopman at gmail.com
Sat Feb 10 15:44:44 CET 2007


On Sat, 10 Feb 2007 22:10:52 +1000
Jonathan McManus <jonathan at acss.net.au> wrote:

> It's pretty easy to make this work, actually. The issue is in the
> "doSomething" method.
> 
> > >>>class Foo(object):
> > >>>	def method(self, arg):
> > >>>		print arg
> > 
> > >>>def doSomething(object, func):
> > >>>	object.func("test")
> 
> Here, it's looking for a method of the "Foo" object (object) called
> "func" (AttributeError: 'Foo' object has no attribute 'func'), instead
> of replacing "func" with "Foo.method". 
> 
> What you need to do is:
> 
> >>> def doSomething (object, func):
> >>>	func(object, "test")
> 
> This means that you are calling the method (explicity passed as being
> a method of Foo), as well as supplying the actual object as the first
> argument (the required self for classes).
> 
> >>> object = Foo()
> >>> doSomething(object, Foo.method)
> test
> 
> Hope that helps.
> 


Thanks,
that I've didn't come up with that myself!
It's indeed easy!


More information about the Tutor mailing list