Created
April 28, 2011 20:15
-
-
Save adeel/947223 to your computer and use it in GitHub Desktop.
A subclass of dict that looks for attributes if the key lookup fails.
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 MyDict(dict): | |
| def get(self, key): | |
| return self.get_key_or_attr(key) | |
| def __getitem__(self, key): | |
| return self.get_key_or_attr(key) | |
| def get_key_or_attr(self, key): | |
| if self.has_key(key): | |
| return dict.__getitem__(self, key) | |
| else: | |
| return self.__getattribute__(key) | |
| @property | |
| def name(self): | |
| return "%s %s" % (self.get("first_name"), self.get("last_name")) | |
| d = MyDict({"first_name": "James", "last_name": "Bond"}) | |
| print d["name"] | |
| print d.get("name") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment