[Tutor] classproperty for Python 2.7 (read-only enough)

Alan Gauld alan.gauld at yahoo.co.uk
Tue Apr 18 10:51:32 EDT 2017


On 18/04/17 11:00, Thomas Güttler wrote:
> I would like to have read-only class properties in Python.

Is there a specific reason why? Do you think for example
that users of the class will deliberately try to modify
the attribute? Normally in Python we leave all attributes
public and unprotected (possibly with a naming hint) and
rely on our users being sensible.

> I want to be a user of class properties, not an implementer of the details.

I'm not sure what exactly you mean by that but...

> I am using Python 2.7 and attribute getters would be enough, no attribute setter is needed.
> 

The default for @property is a read only attribute so

class Spam(object):
   @property
   def eggs(self):
       return self._eggs

   def __init__(self,value):
       self._eggs = value   #initialise it

s = Spam(66)

print s.eggs    # ok
s.eggs = 666    # error, read only.
s._eggs = 666  # can be set
print s._eggs  # still 66
print s.eggs    # oops is now 666

Is that sufficient? If so easy.

But if you want to prevent access to _eggs
from outside that's trickier. But you would
need a very good reason to complicate your
life that much...

Or do you really want a class level property?
In which case refer to Peter's comment.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list