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

Scott David Daniels Scott.Daniels at Acm.Org
Fri May 1 12:33:19 EDT 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):
>>     ...
>>     def function2(self, passedFunction=SomeClass.doNothing):
>>         print "Running passed function"
>>         passedFunction()
>> ...
> 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!

Careful, bearophiles' answer remains the best one.

The only reason your example worked is that you had already had
SomeClass defined (probably from a previous experiment).
At the time you are executing the "def" statements for the
methods of SomeClass, SomeClass is not yet defined.  the default
arguments are evaluated at "def" time, but the method body is
evaluated at methd invokation time (well past the time SomeClass
is fully built.

Typically, classmethod is used to provide alternate constructors
for a class, though it does have other uses.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list