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

Dave Angel davea at ieee.org
Fri May 1 20:47:30 CEST 2009


zealalot wrote:
> On May 1, 10:50 am, CTO <debat... at gmail.com> wrote:
>   
>> Make doNothing a classmethod.
>>
>> class SomeClass:
>>
>>     @classmethod
>>     def doNothing(cls):
>>         pass
>>
>>     def function1(self):
>>         print "Running function 1"
>>
>>     def function2(self, passedFunction=meClass.doNothing):
>>         print "Running passed function"
>>         passedFunction()
>>
>> someObject =omeClass()
>> someObject.function2()
>> someObject.function2(someObject.function1)
>>     
>
> It's not surprising, but I've never heard of a classmethod before.
> Basically, I read that it basically removes the need for the 'self'
> argument.  Very cool!
>
> And thanks for the quick response,
>
> - Zealalot
>
>   
As you've probably figured out by now, that also gets an error, since 
you can't refer to the SomeClass  until the definition is complete.  
Better is either the sentinel approach, or defining the function outside 
the class.  Note that since the signature must match the passed 
function, you presumably need neither a self nor a cls.  So keep it 
simple and define doNothing as a top-level function.

But it's worth expanding on the notion of a classmethod.  This type of 
function is callable with any object, or just with the class name 
itself.  But it doesn't have an access to instance attributes.  That's 
good, but not very common.  Class attributes are more common, and 
they're attributes which are shared among all the objects of the class.





More information about the Python-list mailing list