Immutability

Bruno Desthuilliers onurb at xiludom.gro
Wed Jun 28 06:44:31 EDT 2006


Nick Maclaren wrote:
> The way that I read it, Python allows only values (and hence types)
> to be immutable,

I don't understand this sentence. Some types are immutable, some are
not. This has nothing to do with "values" (FWIW, everything in Python is
an object, there's no 'primitive type' vs 'object type' distinction)

> and not class members. 

If an attribute is of an immutable type, it will still be immutable.

If what you want is 'read-only' attributes, then use properties:

class MyClass(object):
  def __init__(self, name):
    self._name = name
  name = property(fget=lambda self : self._name)

>>> m = MyClass('parrot')
>>> m.name
'parrot'
>>> m.name = "toto"
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
AttributeError: can't set attribute
>>>

> The nearest approach to the
> latter is to use the name hiding conventions.

naming conventions are used to denote what's API and what's
implementation. But this won't make an attribute read-only. If you want
an attribute to be part of the API *but* read-only, use the solution above.

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