Best way to control assignment to attribute?

wes weston wweston at att.net
Wed Feb 4 12:08:07 EST 2004


Frank,
    See __slots__; not sure if there's a newer/better way.

wes



Frank Millman wrote:
> 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
> checks.
> 
> From reading the manuals, this is one way to do it.
> 
> class frank:
>     def __init__(self,x):
>         self.setval_x(x)
> 
>     def __setattr__(self,name,value):
>         if name == 'x':
>             raise 'cannot change value of x - use setval_x(value)'
>         else:
>             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.
> 
> Thanks
> 
> Frank Millman




More information about the Python-list mailing list