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

Scott David Daniels Scott.Daniels at Acm.Org
Fri May 1 15:13:58 EDT 2009


Steven D'Aprano wrote:
> On Fri, 01 May 2009 07:35:40 -0700, 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....
> 
> My first instinct is to say "Don't do that!", but let's see if there's a 
> way to get what you want. It's actually very easy: just put the 
> definition of the passed method before the method you want to use it in, 
> then refer to it by name *without* self.
> 
> However, there is a catch: you need to manually pass in the instance, 
> instead of letting Python do it for you.
> 
> class Spam(object):
>     def ham(self):
>         return "ham"
>     def spam(self, func=ham):
>         return "spam is a tasty %s-like food product" % func(self)

But you don't quite get the behavior the OP wanted, which was to allow
(text-producing in this case) methods as the argument:

 >>> obj = Spam()
 >>> obj.spam()
  'spam is a tasty ham-like food product'
 >>> obj.spam(obj.ham)
Traceback (most recent call last):
   File "<pyshell#271>", line 1, in <module>
     obj.spam(obj.ham)
   File "<pyshell#268>", line 5, in spam
     return "spam is a tasty %s-like food product" % func(self)
TypeError: ham() takes exactly 1 argument (2 given)

Now it is tough to use obj.

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



More information about the Python-list mailing list