Advertisement
Guest User

JS-like dicts implementation (fixed typo)

a guest
May 9th, 2012
188
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.05 KB | None | 0 0
  1. #!/usr/bin/env python
  2. # coding: utf-8
  3.  
  4. # JS-like dictionary
  5. class jsdict:
  6.  
  7.     # Request an item
  8.     def __getitem__(self, i):
  9.         try:
  10.             return self.__dict__[i]
  11.         except KeyError:
  12.             raise AttributeError()
  13.  
  14.     # Set an item
  15.     def __setitem__(self, i, x):
  16.         self.__dict__[i] = x
  17.  
  18.     # Delete an item
  19.     def __delitem__(self, i):
  20.         del self.__dict__[i]
  21.  
  22.  
  23.     # Return as a string
  24.     def __str__(self):  return self.__dict__.__str__()
  25.  
  26.     # Returns the dict representation
  27.     def __repr__(self): return self.__dict__.__repr__()
  28.  
  29.  
  30. # Tests
  31. if __name__ == "__main__":
  32.     d = jsdict()
  33.     d['test'] = "test"
  34.     print d['test'] == "test"
  35.     print d.test == "test"
  36.  
  37.     d.test = "test2"
  38.     print d['test'] == "test2"
  39.     print d.test == "test2"
  40.  
  41.     print d
  42.  
  43.     del d.test
  44.     try:
  45.         x = d.test
  46.         print "False"
  47.     except AttributeError:
  48.         print "True"
  49.  
  50.     try:
  51.         x = d['test']
  52.         print "False"
  53.     except AttributeError:
  54.         print "True"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement