Created
May 1, 2016 07:07
-
-
Save arbinish/6561c27f54237c1b4e999b05a3960514 to your computer and use it in GitHub Desktop.
python classes
This file contains 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 AttrStorage(dict): | |
def __init__(self, fields=None, **kwargs): | |
""" only allow keys defined in fields """ | |
self.fields = () | |
if fields: | |
self.fields = fields | |
super(AttrStorage, self).__init__(kwargs) | |
def __getitem__(self, name): | |
val = super(AttrStorage, self).get(name) | |
if val: | |
return val | |
raise KeyError(name) | |
def __setitem__(self, k, v): | |
""" Additionaly restrict changing the value of keys once set """ | |
if len(self.fields) and k not in self.fields: | |
raise AttributeError("{0}: not allowed".format(k)) | |
try: | |
self.__getitem__(k) | |
except KeyError: | |
pass | |
else: | |
raise RuntimeError('Read-only attribute: {0}'.format(k)) | |
return super(AttrStorage, self).__setitem__(k, v) | |
class Person(object): | |
__slots__ = ['_fields'] | |
def __init__(self, name, age): | |
self._fields = AttrStorage(('name', 'age')) | |
self._fields['name'] = name | |
self._fields['age'] = age | |
@property | |
def name(self): | |
return self._fields['name'] | |
@property | |
def age(self): | |
return self._fields['age'] | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment