Custom Search

Saturday, January 22, 2011

python defining special methods __eq__ and __le__ on a class

python defining special methods __eq__ and __le__ on a class

class A:

def __init__(self, num):
self.num = num

def __add__(self, second_num):
return self.num + second_num

def __eq__(self, second_num):
if self.num == second_num:
print "\nNumbers are equal"
else:
print "\nNumbers are not equal"

def __le__(self, second_num):
if self.num <= second_num:
print "\n"+str(self.num)+" is less than or equal to "+str(second_num)
else:
print "\n"+str(self.num)+" is grater than "+str(second_num)

a1 = A(10)

print "-------a1 + 10-------", a1 + 40

print "-------a1 == 10-------", a1 == 10

print "-------a1 == 10-------", a1 == 20

print "-------a1 <= 30 -------", a1 <= 30

print "-------a1 <= 5 -------", a1 <= 5



OUTPUT
=======
-------a1 + 10------- 50
-------a1 == 10-------
Numbers are equal
None
-------a1 == 10-------
Numbers are not equal
None
-------a1 <= 30 -------
10 is less than or equal to 30
None
-------a1 <= 5 -------
10 is grater than 5
None

No comments:

Post a Comment