How do these Java concepts translate to Python?
onurb at xiludom.gro
Fri Aug 12 11:09:40 CEST 2005
> Fausto Arinos Barbuto wrote:
>>>1. Where are the access specifiers? (public, protected, private)
>> AFAIK, there is not such a thing in Python.
> So everything is public? I know that you can prefix a member with
> underscores to make something private,
The "2 leadings underscore name mangling" scheme is intented to protect
"sensible" attributes from being accidentally overriden by derived
classes, not to prevent access to the attribute.
self.__baaz = 42
f = Foo()
> but how about protected, for
object._protected_attribute is enough to tell anyone not to mess with
this attribute. Believe it or else, but this happens to work perfectly.
And BTW, don't bother making all your attributes "protected" or
"private" then writing getters and setters, Python has a good support
for computed attributes, so you can change the implementation without
problem (which is the original reason for not-public attributes):
# first version:
self.baaz = 42 # public attribute
# later we discover that we want Foo.baaz to be computed:
self.baaz = 42
def _set_baaz(self, value):
if value < 21 or value > 84:
raise ValueError, "baaz value must be in range 21..84"
self._baaz = value
return self._baaz * 2
baaz = property(fget=_get_baaz, fset=_set_baaz)
Easy as pie, uh ?-)
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