Last active
July 6, 2019 02:29
-
-
Save sujeetkv/5e53d229fcc73a3f20cea1a7d2c22cdc to your computer and use it in GitHub Desktop.
Make a dictionary behave like an object, with attribute-style access.
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 DictObject(dict): | |
"""Dict behaving like an object, with attribute-style access.""" | |
__strict_attr__ = True | |
__attr_default__ = None | |
def __getattr__(self, name): | |
try: | |
return self[name] | |
except KeyError: | |
if self.__strict_attr__: | |
raise AttributeError(name) | |
else: | |
return self.__attr_default__ | |
def __setattr__(self, name, value): | |
if name not in ('__strict_attr__', '__attr_default__'): | |
self[name] = value |
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 MyDict(DictObject): | |
pass | |
d = MyDict(one=1, two=2) | |
print(d.one) | |
print(d['one']) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment