Pages

Sunday, December 12, 2010

How to make object support indexing in python (object[index])

Sometime, we may want the object can do like array or dict that use object[index] instead of object.getsomthing() for making it more convenience. So, the solution is easy, python provide us the attribute for creating object support indexing that is "__getitem__(key)".

For example
class Test:
 def __getitem__(self,key):
  return 0

a = Test()
print a[2]
print a["hello"]
We can modify its behavior in the method.
More information about python attributes at: http://docs.python.org/reference/datamodel.html

No comments:

Post a Comment