Reputation: 4545
i want to store a certain kind of object in a dictionary. the object has an attribute called 'lastAccessDate',whenever the program access the object, i hope the object's attribute update to current system time,which like this
def getValue(key):
obj = objectDict.get(key,None)
if obj is not None:
obj.lastAccessDate = getSystemDate()
return obj
the program must throught this api to access the object, otherwise it's would be a bug.i hope i can operate the dict like normal dict,when i use objectDict[key] or objectDict.get() to access the key,it will do this thing automatically.how to implement it in python?
Upvotes: 1
Views: 238
Reputation: 33197
You can re-implement or provide the []
accessor via __getitem__
which would appear to make your custom object be a dict. If you need to provide set support, implement __setitem__
http://docs.python.org/2/reference/datamodel.html#emulating-container-types
Upvotes: 1