Stop assignment of a class attribute?
Al Gonzalez
alberto at mindspring.com
Sun Aug 19 17:57:02 EDT 2001
I can overload the __setattr__ and __delattr__ to make instance attributes
immutable, but I don't see how it can be done for class attributes. Does
anyone have any ideas?
class Spam:
"""Information that shouldn't be changed"""
name = "My SPAM!"
def __init__(self):
self.X = "test"
# block setting or deleting of attributes
def __setattr__(self, name, value):
if self.__dict__.has_key(name):
raise TypeError, "Attributes of this class are immutable!\nThey
may not be changed nor deleted."
else:
self.__dict__[name]=value
def __delattr__(self, name):
if self.__dict__.has_key(name):
raise TypeError, "Attributes of this class are immutable!\nThey
may not be changed nor deleted."
a = Spam()
a.X = "new test" # will raise an error
Spam.name = "Guindalin" # will not raise an error
a.name = "George!" # will also not raise an error
More information about the Python-list
mailing list