A matter of style: class.foo = bar vs. class.set_foo(bar)

Alex Martelli aleaxit at yahoo.com
Sat Nov 11 11:41:55 EST 2000


"Syver Enstad" <syver.enstad at sensewave.com> wrote in message
news:8ujkua$seu$2 at troll.powertech.no...
>
> "Aahz Maruch" <aahz at panix.com> wrote in message
> news:8uhkk9$2r5$1 at panix2.panix.com...
> > Generally speaking, because Python does not have private parts, you only
> > use a method when you want to trigger an action in addition to just
> > changing the variable's value.
> It does have a kind of privacy if you prefix your instance variables with
> two underscores "__". Python will then mangle the name if used outside the
> class so that it will be extremely painful to use it directly. The problem
> then is using the variable from a derived class, it seems you'll have to
use
> accessors then too.

If you're only _reading_ the attribute, __getattr__ may help, e.g.:
    def __getattr__(self, name):
        try: self.__dict__['_X__'+name]
        except KeyError: raise AttributeError, name
(if your class's name is X).

Your derived class will need to take this into account if, and
only if, it also implements __getattr__ (it will have to delegate
to X.__getattr__ explicitly if need be, as always!).


Alex






More information about the Python-list mailing list