Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/env python
- # coding: utf-8
- # JS-like dictionary
- class jsdict:
- # Request an item
- def __getitem__(self, i):
- try:
- return self.__dict__[i]
- except KeyError:
- raise AttributeError()
- # Set an item
- def __setitem__(self, i, x):
- self.__dict__[i] = x
- # Delete an item
- def __delitem__(self, i):
- del self.__dict__[i]
- # Return as a string
- def __str__(self): return self.__dict__.__str__()
- # Returns the dict representation
- def __repr__(self): return self.__dict__.__repr__()
- # Tests
- if __name__ == "__main__":
- d = jsdict()
- d['test'] = "test"
- print d['test'] == "test"
- print d.test == "test"
- d.test = "test2"
- print d['test'] == "test2"
- print d.test == "test2"
- print d
- del d.test
- try:
- x = d.test
- print "False"
- except AttributeError:
- print "True"
- try:
- x = d['test']
- print "False"
- except AttributeError:
- print "True"
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement