What are modules really for?

bruno modulix onurb at xiludom.gro
Wed Aug 10 13:25:40 EDT 2005


Tito wrote:
>> [1]  'aName' => public, '_aName' => protected, '__aName' => private
> 
> 
> I didn't know this one, as I am quite new to Python. Is it really
> general use?

Yes, it's the convention.

Well, to be more exact, this is:

name => interface (intended for public use)
_name => implementation (not intented for public use)
__name => mangled (should not be hidden or overriden) [1]
__name__ => magic (has special meaning for the Python interpreter) [2]

BTW, from module import * tends to only import 'public' symbols, so you
can use _name to prevent _name being imported by accident.

[1] The purpose here is not to enforce privacy, but to protect the
symbolf from being accidentaly overriden or hidden.
given:
class Foo(object):
  def __init__(self, name):
    self.__name = name
f = Foo('foo')

You'll have to use :
f._Foo__name

to access foo.__name from outside the class (this hold for derived
classes too).


[2] __name__ attributes (variables and functions) usually have special
behaviours attached to them. For exemple,
- obj.__init__(self, ...) is called on object initialisation
- seq.__len__() is called by len(seq),
- obj.__str__() is called by str(obj)
- obj.__add__ is the '+' operator  called by obj1 + obj2 ->
obj1.__add__(self, obj2),
- obj.__getattr__(self, name) is called when you lookup an inexistant
attribute of obj, etc...

You'll find all this (and much more) in the doc.

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