Next / Previous / Contents / TCC Help System / NM Tech homepage

14.15. property(): Create an access-controlled attribute

The purpose of this function is to create a property of a class. A property looks and acts like an ordinary attribute, except that you provide methods that controls access to the attribute.

There are three kinds of attribute access: read, write, and delete. When you create a property, you can provide any or all of three methods that handle requests to read, write, or delete that attribute.

Here is the general method for adding a property named p to a new-style class C.

class C(...):
    def R(self):
        ...read method...
    def W(self, value):
        ...write method...
    def D(self):
        ...delete method...
    p = property(R, W, D, doc)
    ...

where:

As an example, here is a small class that defines a property named x:

class C(object):
    def __init__(self):
        self.__x=None
    def getx(self):
        print "+++ getx()"
        return self.__x
    def setx(self, v):
        print "+++ setx(%s)" % v
        self.__x  =  v
    def delx(self):
        print "+++ delx()"
        del self.__x
    x=property(getx, setx, delx, "Me property 'x'.")

Assuming that class is defined, here is a conversational example.

>>> c=C()
>>> print c.x
+++ getx()
None
>>> print C.x.__doc__
Me property 'x'.
>>> c.x=15
+++ setx(15)
>>> c.x
+++ getx()
15
>>> del c.x
+++ delx()
>>> c.x
+++ getx()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 6, in getx
AttributeError: 'C' object has no attribute '_C__x'