How do these Java concepts translate to Python?

bruno modulix onurb at xiludom.gro
Fri Aug 12 11:09:40 CEST 2005


Ray wrote:
> Fausto Arinos Barbuto wrote:
> 
>>Ray 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.

class Foo(object):
  def __init__(self):
    self.__baaz = 42

f = Foo()
print f._Foo__baaz

> but how about protected, for
> example?

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:
class Foo(object):
  def __init__(self):
     self.baaz = 42 # public attribute

# later we discover that we want Foo.baaz to be computed:
class Foo(object):
  def __init__(self):
     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

  def _get_baaz(self):
      return self._baaz * 2

  baaz = property(fget=_get_baaz, fset=_set_baaz)

Easy as pie, uh ?-)


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