Property Descriptor - Public Getter, Private Setter

James Stroud jstroud at mbi.ucla.edu
Wed Jul 18 16:51:56 EDT 2007


gamehack wrote:
> Hi all,
> 
> I was looking around the net to figure out how I can use the
> property() descriptor to make a property readable by everyone and only
> settable by the class or any derived classes. Thanks.
> 
> Regards,
> gh
> 

Congratulations, you have discovered a principal use of properties--to 
restrict access! But how? By the honor system, of course, and some 
clever naming techniques and documentation. Below we see all of the 
essential components.

     1. clever naming -- our attribute is prepended with an underscore,
                         signifying its special status as an internal
                         name and will not be exposed to the API.
     2. documentation -- we let our users know about the value property
     3. properties    -- we make a property named value that is exposed
                         to the API, but we don't expose _value as it
                         is not available beyond the class and subclasses
                         implicitly, by virtue of clever naming (see 1)

class C(object):
   """
   Instances of this class are endowed with a 'value' property.
   This property is read-only for users of the API. Have a Nice Day.
   """
   def __init__(self):
     self._value = None
   def get_value(self):
     return self._value
   value = property(get_value)


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