{article Dive into Python}{title} {text} {/article}

>>> d = dict([("age", 25)])
>>> def __repr__(self): return repr(self.data)

>>> def __cmp__(self, dict):
if isinstance(dict, UserDict):
return cmp(self.data, dict.data)
else:
return cmp(self.data, dict)


>>> def __len__(self): return len(self.data)

>>> def __delitem__(self, key): del self.data[key]

>>> print repr(d)
SyntaxError: invalid syntax
>>> print (repr(d))
{'age': 25}
>>>

__repr__ is a special method that is called when you call repr(instance). The repr function
is a built−in function that returns a string representation of an object. It works on any object, not just
class instances. You're already intimately familiar with repr and you don't even know it. In the
interactive window, when you type just a variable name and press the ENTER key, Python uses repr
to display the variable's value. Go create a dictionary d with some data and then print repr(d) to
see for yourself.

__cmp__ is called when you compare class instances. In general, you can compare any two Python
objects, not just class instances, by using ==. There are rules that define when built−in datatypes are
considered equal; for instance, dictionaries are equal when they have all the same keys and values, and
strings are equal when they are the same length and contain the same sequence of characters. For class
instances, you can define the __cmp__ method and code the comparison logic yourself, and then you
can use == to compare instances of your class and Python will call your __cmp__ special method for
you.

__len__ is called when __len__ is called when you call len(instance). The len function is a built−in function that
returns the length of an object. It works on any object that could reasonably be thought of as having a
length. The len of a string is its number of characters; the len of a dictionary is its number of keys;
the len of a list or tuple is its number of elements. For class instances, define the __len__ method and code the length calculation yourself, and then call len(instance) and Python will call your
__len__ special method for you.

__delitem__ is called when you call del instance[key], which you may remember as the
way to delete individual items from a dictionary. When you use del on a class instance, Python calls
the __delitem__ special method for you.