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__(sel f,name,value):
if name == 'x':
raise 'cannot change value of x - use setval_x(value) '
else:
self.__dict__[name] = value
def setval_x(self,v alue):
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
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__(sel f,name,value):
if name == 'x':
raise 'cannot change value of x - use setval_x(value) '
else:
self.__dict__[name] = value
def setval_x(self,v alue):
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
Comment