Overload __sub__ method for subtract operator
Overload __sub__
class Number:# w ww. j a v a 2s . c o m
def __init__(self, start): # on Number(start)
self.data = start
def __sub__(self, other): # on instance - other
return Number(self.data - other) # result is a new instance
X = Number(5) # Number.__init__(X, 5)
Y = X - 2 # Number.__sub__(X, 2)
print Y.data # Y is new Number instance
The code above generates the following result.