utility functions within a class?

bruno at modulix onurb at xiludom.gro
Tue May 9 04:51:25 EDT 2006


John Salerno wrote:
> blair.bethwaite at gmail.com wrote:
> 
>> I'm having trouble deciphering what this bit means - "but these
>> functions will be called from another method in the class, not from the
>> instance itself", I don't think it makes sense.
> 
> 
> Yeah, I'm starting to see that as I tried to implement it. Here's what I
> came up with, which works:
> 
> def generate(self, filename):
>     self.head = self.generate_head()
>     self.body = self.generate_body()
> 
> So the two generate_* methods are called from within another class
> method,

here, generate() is *not* a class method, it's an instance method (which
is the default).

> and it seemed necessary to still call them from an instance.
> What I originally meant was that they would not be called from an
> instance *outside* the class itself, i.e. they won't be used when
> writing another script, they are only used by the class itself.

Yeps, that's pretty common in any OO language. In most mainstream OOPLs,
these methods would have the 'protected' access restriction modifier. In
Python, we rely on the convention that an attribute whose name is
prefixed with a single underscore is an implementation detail - not part
of the API - and should not be called by client code. Just renaming
these two methods is enough to warn users of your code that they're on
their own if they start messing with them.

-- 
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