Overload comparison operators

Overload comparison operators


class MyClass(object):
    def __init__(self, name):
        print "creating MyClass"
        self.name = name# ww w  .  j a  v a2s  . com

    def __str__(self):
        rep = "MyClass object\n"
        rep += "name: " + self.name + "\n"
        return rep

    def __cmp__(self, other):
        print("called")
        if self.name > other.name:
            return 1
        if self.name < other.name:
            return -1
        if self.name == other.name:
            return 0      

    def talk(self):
        print "Hi.  I'm", self.name, "\n"

# main
crit1 = MyClass("A")
crit1.talk()

crit2 = MyClass("B")
crit2.talk()

print crit1 > crit2

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules