Passing a function as an argument from within the same class?

Peter Otten __peter__ at web.de
Fri May 1 11:41:27 EDT 2009


CTO wrote:

> Make doNothing a classmethod.
> 
> class SomeClass:
> 
>     @classmethod
>     def doNothing(cls):
>         pass
> 
>     def function1(self):
>         print "Running function 1"
> 
>     def function2(self, passedFunction=SomeClass.doNothing):
>         print "Running passed function"
>         passedFunction()
> 
> someObject = SomeClass()
> someObject.function2()
> someObject.function2(someObject.function1)

To make that run without error you have to jump through a lot of hoops:

class SomeClass(object):
    @classmethod
    def doNothing(cls):
        pass
    def function1(self):
        print "Running function 1"

def function2(self, passedFunction=SomeClass.doNothing):
    print "Running passed function"
    passedFunction()

SomeClass.function2 = function2

someObject = SomeClass()
someObject.function2()
someObject.function2(someObject.function1)

And if you don't need access to the instance you may not need access to the 
class either. In this case you can simplify:

def doNothing():
    pass

class SomeClass(object):
    def function1(self):
        print "Running function 1"
    def function2(self, passedFunction=doNothing):
        print "Running passed function"
        passedFunction()

If you do need information about the state of the instance you can either 
pass it explicitly

class SomeClass(object):
    def doNothing(self):
        pass
    def function1(self):
        print "Running function 1"
    def function2(self, passedFunction=doNothing):
        print "Running passed function"
        passedFunction.__get__(self)()

or (better, I think) use a sentinel as shown by Bearophile.

Peter




More information about the Python-list mailing list