Cmp and Classes and Dictionaries

cmp () works with many object types. For example, if left undefined, it works with class instances just as id or i s does. As with numeric objects, cmp () returns 0 if the objects are equal. Here's an illustration.

Create two class instances.

>>> ci1,ci2 = myclass2(),myclass2() Compare them.

Even though the values are the same, the instances are unequal because the default is to check object identity (to make sure that the variable references the same object).

Compare one instance to itself.

Sincecmp () checks identity for equality, comparing an object to itself returns 0, which means equality.

Thecmp () method defines the behavior of the equality operators. That means that the following is like using the identity operator:

Chapter 8 has an example of_cmp_defined for the Addres s c lpss. Here's ag exceipt:

Compares one address instance to another.

If the address instances are equal the __cmp__ returns 0. If the address instances are not equal then we return a non-zero value.

# To implement this all we do is compare

# the dictionaries of the class

# The __dict__ member of the instance holds

# all of the instance fields

# in a dictionary return cmp(self.__dict_ ,other.__dict_)

This compares all attribute values of one instance of Addres s with those of another instance. Remember, the default is just to compare identity.

Was this article helpful?

0 0

Post a comment