utility functions within a class?

bruno at modulix onurb at xiludom.gro
Tue May 9 04:46:01 EDT 2006


John Salerno wrote:
> John Salerno wrote:
> 
>> jeffshannon at gmail.com wrote:
>>
>>> Even if you don't end up referring to self or any instance
>>> attributes within the method
>>
>>
>> Hmm, follow-up: I *do* plan to refer to instance attributes inside
>> these methods (self.something), but does that require that they be
>> instance methods, or can they still reference 'self' since they are
>> inside the class?
>>
>> They won't be called directly from an instance, which is why I
>> wondered about making them static or class methods, but can static or
>> class methods use self, or does it have to be an instance method in
>> that case?
> 
> 
> Ugh, sorry about another post, but let me clarify: In these utility
> functions, I need to refer to an attribute of an instance,

So you want ordinary methods.

> but these
> functions will be called from another method in the class, not from the
> instance itself.

yes, they will:

class Parrot(object):
   def _func1(self, whatever):
     print whatever

  def talk(self):
     self._func1('vroom')

> Is this even possible, or would 'self' have no meaning
> when used this way?

You probably noticed that 'self' (or whatever you name it - but better
to stick to convention) *must* be defined as the first param of a
'method'. The reason for it is that what we commonly call 'methods' are
in fact plain Python functions. It's only when they are looked up on an
instance that they are wrapped into a 'method' object (read about the
descriptor protocol to learn how...), that in turn calls the function,
passing it the instance as first param.

For saying it short (warning: over-simplification ahead), the usual
method call idiom:

  myObj.myMethod(arg)

is syntactic sugar for:

  myObj.__class__.myMethod(myObj, arg)


HTH.

-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list