Operator Overloading: add, sub, mul, div : Operator Overloading « Class « Python Tutorial

Home
Python Tutorial
1.Introduction
2.Data Type
3.Statement
4.Operator
5.String
6.Tuple
7.List
8.Dictionary
9.Collections
10.Function
11.Class
12.File
13.Buildin Function
14.Buildin Module
15.Database
16.Regular Expressions
17.Thread
18.Tkinker
19.wxPython
20.XML
21.Network
22.CGI Web
23.Windows
Python Tutorial » Class » Operator Overloading 
11.5.1.Operator Overloading: add, sub, mul, div
__add__ : Implements the plus "+" operator.
__sub__ : Implements the minus "-" operator.
__mul__ : Implements the multiplication "*" operator.
__div__ : Implements the division "/" operator.


class Double(object:
    def __init__(self:
        self.value = 0

    def __add__(self, value:
        return self.value + * value

    def __sub__(self, value:
        return self.value - * value

    def __mul__(self, value:
        return self.value * (2*value)

    def __div__(self, value:
        return self.value / (2*value)

    def __cmp__(self, value:
        if self.value < (value*2:
            return -1
        elif self.value == value*:
            return 0
        else :
            return 1

d = Double()
d.value = 10

print d + 2
print d - 2
print d * 2
print d / 1

if d < : print "Less than 5"
else : print "Not less than 5"

d.value = 10
if d == :
       print "Yes!"
else :
       print "no..."
11.5.Operator Overloading
11.5.1.Operator Overloading: add, sub, mul, div
11.5.2.Operator Overloading: sub
11.5.3.Classes Can Intercept Python Operators
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.