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 to a new-style class
p.
C
classC(...): defR(self): ...read method... defW(self, value): ...write method... defD(self): ...delete method...p= property(R,W,D,doc) ...
where:
is a method
that takes no arguments and returns the effective
attribute value. If omitted, any attempt to read that
attribute will raise RAttributeError.
is a method
that takes one argument and sets the attribute to that
argument's value. If omitted, any attempt to write that
attribute will raise WAttributeError.
is a method
that deletes the attribute. If omitted, any attempt to
delete that attribute will raise DAttributeError.
is a
documentation string that describes the attribute. If
omitted, defaults to the documentation string of the
doc method if
any, otherwise RNone.
To retrieve a property's documentation, use this form:
C.p.__doc__
where is
the class name and C is the property name.
p
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'