best practices for making read-only attributes of an object

James Stroud jstroud at ucla.edu
Wed Mar 15 15:12:06 EST 2006


bruno at modulix wrote:
> Tim Chase wrote:
>>
>>class Foo:
> 
> old-style classes are deprecated, please use new-style classes:
> class Foo(object):
> 

This should be re-phrased to 'Use new-style classes, or else!'

py> class Foo:
...   def __init__(self, color):
...     self._color = color
...   color = property(fget=lambda self: self._color)
...
py> p = Foo('red')
py> p.color
'red'
py> p.color = 'green'   # shouldn't be able to do this
py> p.color
'green'
py>
py> class Parrot(object):
...   def __init__(self, color):
...     self._color = color
...   color = property(fget=lambda self: self._color)
...
py> p = Parrot('orange')
py> p.color
'orange'
py> p.color = 'pink'
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
AttributeError: can't set attribute

James

-- 
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095

http://www.jamesstroud.com/



More information about the Python-list mailing list