Freezing data members of a class!
Sunil Hadap
Sunil.Hadap at cui.unige.ch
Fri Feb 4 14:21:34 EST 2000
Hello, I hope this is not too trivial question
I want to stop the user from adding any more data members to instance of
a class than those added by the constructor.
Secondly I want to prevent the user from chaning type of the data member
(trough assignment) which gets defined only construction time. I have
done the following. Is this the best way!
class SuData:
def __setattr__(self,attrname,value):
print "__setattr__ for %s called with value " % attrname, value
if self.__dict__.has_key(attrname):
if type(self.__dict__[attrname]) is type(value):
self.__dict__[attrname] = value
else:
raise AssertionError, attrname
else:
raise AssertionError, attrname
def __delattr__(self,attrname):
raise AssertionError, attrname
class SuNumericData(SuData):
def __init__(self, initial):
self.__dict__['_data'] = initial
Python is fun to dig into! Thanks a lot
Sunil
More information about the Python-list
mailing list