Passing a method indirectly

André andre.roberge at gmail.com
Sat Mar 4 19:04:01 EST 2006


swisscheese wrote:
> I'm trying to write a function that takes an arbitrary object and
> method.
> The function applies the method to the object (and some other stuff).
> I get error "Test instance has no attribute 'method' "
> How can I make this work?
>
> def ObjApply (object,method):
> 	object.method ()
>
> class Test:
> 	def test1 (self): print "Hello"
> 	def test2 (self):
> 		ObjApply (self,self.test1)
>
> ta = Test ()
> ta.test2 ()

You need to add one line (2nd one below).

def ObjApply (object, method):
    object.method = method
    object.method()

class Test:
    def test1 (self): print "Hello"
    def test2 (self):
        ObjApply (self, self.test1)

ta = Test ()
ta.test2 ()

André




More information about the Python-list mailing list