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

Terry Reedy tjreedy at udel.edu
Fri May 1 23:37:48 CEST 2009


zealalot wrote:
> So, I'm trying to come up with a way to pass a method (from the same
> class) as the default argument for another method in the same class.
> Unfortunately though, I keep getting "self not defined" errors since
> the class hasn't been read completely before it references itself.
> 
> Is there a better way of doing this?
> 
> --- CODE ---
> 
> class SomeClass():
>     def doNothing(self):
>         pass
>     def function1(self):
>         print "Running function 1."
>     def function2(self, passedFunction=self.doNothing):
>         print "Running passed function."
>         passedFunction()
> 
> someObject = SomeClass()
> someObject.function2(someobject.function1)

As Stephen D'Aprano indicated, this is very easy

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

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

produces (with 3.0.1)

Running passed function.
Doing nothing
Running passed function.
Running function 1.

Key 1: a class statement introduces a new local namespace.  The body of 
the class statement is executed in that namespace.  Default arguments 
are evaluated, when a def statement is executed, in the local namespace 
of that def statement.  For methods, that is the local namespace of the 
class.  Hence, 'passedFunction = doNothing' works fine.

Key 2: When a parameter is a function, the signature of the default and 
passed args are effectively part of the required type for the args.  In 
this case, passedFunction is a function with one parameter.  When 
captured, doNothing is not yet a method of the yet-to-become Someclass. 
So non-defaults passed to .function2 do not have to be methods either. 
In Python 3, unbound methods are simply functions anyway.

Terry Jan Reedy




More information about the Python-list mailing list