proposal: accessor methods

jepler epler jepler.lnk at lnk.ispi.net
Sun Jul 16 22:07:05 EDT 2000


class SetAccessor:
    """
(I tested this class, then managed to enhance it with
default_set_only_by_accessor and __attributes__ in posting.  Sigh,
it's too hard to leave simple code alone!  It worked a minute ago,
I swear)

Subclasses may define methods with the name __set_(attribute name)__
to be called when attribute assignments occur.

Furthermore, if .default_set_only_by_accessor is true, assignment to
attributes for which accessors do not exist is an error.

__attributes__ lists attributes which can be set even for
default_set_only_by_accessor objects even in the absence of an accessor
function.
"""
    self.__attributes__ = ()
    self.default_set_only_by_accessor = 0
    def __setattr__(self, attr, value):
        accessor_method = getattr(self, "__set_%s__" % attr, None)
        if accessor_method:
            accessor_method(value)
        else:
            if self.default_set_only_by_accessor \
                    and not attr in self.__attributes__:
                raise TypeError, "read-only attribute %s" % attr
        else:
            self.__dict__[attr] = value

class GetAccessor:
    """
(I didn't actually test this class)

Subclasses may define methods with the name __get_(attribute name)__
to be called when undefined attribute references occcur.
"""
    def __getattr_(self, attr):
        accessor_method = getattr(self, "__get_%s__" % attr, None)
        if accessor_method():
            return accessor_method()
        else:
            raise AttributeError, attr




More information about the Python-list mailing list