Created
October 25, 2012 10:54
-
-
Save lgr/3951990 to your computer and use it in GitHub Desktop.
A class with the attributes that are prevented from being overwritten
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class ReadOnlyAttr: | |
""" A class with the attributes that are defined on the instance | |
creation and cannot be modified later. """ | |
# A tuple of attributes that should remain read-only | |
READ_ONLY_ATTR = ('x', 'y') | |
def __init__(self, *args, **kwargs): | |
""" Takes a list of read-only attributes: %s """ | |
for attr in self.READ_ONLY_ATTR: | |
setattr(self, attr, | |
kwargs.get(attr, '')) | |
# List READ_ONLY_PARAMETERS in the docstring of the class. | |
__init__.__doc__ %= ", ".join(READ_ONLY_ATTR) | |
def __setattr__(self, name, value): | |
""" Prevent the READ_ONLY_ATTR from being overwritten. """ | |
if name in self.__dict__ and name in self.READ_ONLY_ATTR: | |
raise AttributeError("The attribute '%s' cannot be overwritten" | |
% name) | |
else: | |
self.__dict__[name] = value | |
# Examples: | |
# Create an instance | |
roa = ReadOnlyAttr(x="Some value", y=234) | |
# Print the value: | |
print roa.x | |
# The following will raise an exception: | |
roa.x = "New value" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment