Strategies for controling attribute assignment

Tim Peters tim at zope.com
Tue Oct 2 14:47:05 EDT 2001


[Dale Strickland-Clark, weary of __setattr__]
> ...
> I guess I'd like to explicitly declare which attributes are part of
> the public face of the class and which are not.
>
> I assume my approach is as good as any.

Hard to say, unless I get to define "good" <wink>.  Another approach is to
use naming conventions.

Python 2.2's "new-style classes" support customized attribute management
without using __get/set attr__ tricks.  Example:

class Clipped(object):
    def __init__(self, lo, hi):
        "The instance's .x attr is constrained to lo <= .x <= hi"
        assert lo <= hi
        self.lo, self.hi = lo, hi

    def _getx(self):
        return self._x

    def _setx(self, value):
	self._x = min(max(value, self.lo), self.hi)

    x = property(_getx, _setx, doc="a bounded value")

a = Clipped(1, 3)
for i in range(5):
    a.x = i
    print "after setting a.x to", i, "its value is", a.x

That prints

after setting a.x to 0 its value is 1
after setting a.x to 1 its value is 1
after setting a.x to 2 its value is 2
after setting a.x to 3 its value is 3
after setting a.x to 4 its value is 3

"property" is a builtin convenience function in 2.2, but you could write
property() yourself in 2.2 (and without using __get/set attr__).  See the
2.2 PEPs for details about the new "attribute descriptor" protocol.





More information about the Python-list mailing list