Best way to control assignment to attribute?

Frank Millman frank at
Wed Feb 4 16:12:48 CET 2004

Hi all

I want to control the assignment of a value to an attribute. Instead
of allowing it to be changed directly, I want to enforce that a method
is called, which will perform the assignment subject to various

>From reading the manuals, this is one way to do it.

class frank:
    def __init__(self,x):

    def __setattr__(self,name,value):
        if name == 'x':
            raise 'cannot change value of x - use setval_x(value)'
            self.__dict__[name] = value

    def setval_x(self,value):
        ok = 1
        # perform any checks required
        if ok:
            self.__dict__['x'] = value

Is this the best way, or does anyone have any other suggestions?

I notice that an application can beat this by using the __dict__
syntax itself. Is there any way to prevent this? Just curious, it is
not a major concern.

Any comments will be appreciated.


Frank Millman

More information about the Python-list mailing list