Passing a function as an argument from within the same class?
steve at REMOVE-THIS-cybersource.com.au
Fri May 1 19:09:21 CEST 2009
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.
> 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?
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.
def spam(self, func=ham):
return "spam is a tasty %s-like food product" % func(self)
And in use:
>>> obj = Spam()
'spam is a tasty ham-like food product'
More information about the Python-list