Passing a function as an argument from within the same class?
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Fri May 1 13:00:25 EDT 2009
On Fri, 01 May 2009 08:11:01 -0700, 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=SomeClass.doNothing):
>> print "Running passed function"
>> passedFunction()
>>
>> someObject = SomeClass()
>> 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!
Not so.
When you call an ordinary method (an "instance method"), Python
automatically inserts the object itself as the first argument. So you
need to define the method with one extra parameter, self.
(Using the name self is just a convention. You can call it anything you
like.)
For classmethods, Python automatically inserts not the object itself, but
the object's *class* as the first argument. So you still need to define
the method with an extra parameter, only now the convention is to call is
cls rather than self.
Here's an example:
class Test(object):
x = 0 # class attribute
def __init__(self, x):
self.x = x # instance attribute
def spam(self):
print self, self.x
@classmethod
def ham(cls):
print cls, cls.x
And in use:
>>> t = Test(42)
>>> t.spam()
<__main__.Test object at 0xb7cccc6c> 42
>>> t.ham()
<class '__main__.Test'> 0
There is one other related built-in decorator, staticmethod().
staticmethod() tells Python not to pass any extra argument to the method.
That means the inside a static method, you can't refer to either the
instance (self) or the class! Needless to say, there aren't very many
uses for staticmethod().
--
Steven
More information about the Python-list
mailing list