Log in / Register
Home arrow Computer Science arrow Data Structures and Algorithms with Python
< Prev   CONTENTS   Next >

1.5 Operator Overloading

Python provides operator overloading, which is a nice feature of programming languages because it makes it possible for the programmer to interact with objects in a very natural way. Operator overloading is already implemented for a variety of the built-in classes or types in Python. For instance, integers (i.e. the int type) understand how they can be added together to form a new integer object. Addition is implemented by a special method in Python called the add method. When two integers are added together, this method is called to create a new integer object. If you look in the appendices, you'll see examples of these special methods and how they are called.

For example, in Chap. 13 the add method is called by writing x + y where

x is an integer. The methods that begin and end with two underscores are methods that Python associates with a corresponding operator.

When we say that Python supports operator overloading we mean that if you define a method for your class with a name that is operator overloaded, your class will support that operator as well. Python figures out which method to call based on the types of the operands involved. For instance, writing x + y calls the int class

add method when x is an integer, but it calls the float type's add method when x is a float. This is because in the case of the add method, the object on the left hand side of the + operator corresponds to the object on the left hand side of the dot (i.e. the period) in the equivalent method call x. add (y). The object on the left side of the dot determines which add method is called. The + operator is overloaded.

If we wanted to define addition for our Dog class, we would include an add method in the class definition. It might be natural to write boyDog + girlDog to create a new puppy object. If we wished to do that we would extend our Dog class as shown in Sect. 1.5.1.

1.5.1 The Dog Class with Overloaded Addition

1 class Dog:

2 # This is the constructor for the class. It is called whenever a Dog

3 # object is created. The reference called "self" is created by Python

4 # and made to point to the space for the newly created object. Python

5 # does this automatically for us but we have to have "self" as the first

6 # parameter to the init method (i.e. the constructor).

7 def init (self, name, month, day, year, speakText):

8 = name

9 self.month = month

10 = day

11 self.year = year

12 self.speakText = speakText


14 # This is an accessor method that returns the speakText stored in the

15 # object. Notice that "self" is a parameter. Every method has "self" as its

16 # first parameter. The "self" parameter is a reference to the current

17 # object. The current object appears on the left hand side of the dot (i.e.

18 # the .) when the method is called.

19 def speak(self):

20 return self.speakText


22 # Here is an accessor method to get the name

23 def getName(self):

24 return


26 # This is another accessor method that uses the birthday information to

27 # return a string representing the date.

28 def birthDate(self):

29 return str(self.month) + "/" + str( + "/" + str(self.year)


31 # This is a mutator method that changes the speakText of the Dog object.

32 def changeBark(self,bark):

33 self.speakText = bark


35 # When creating the new puppy we don't know it's birthday. Pick the

36 # first dog's birthday plus one year. The speakText will be the

37 # concatenation of both dog's text. The dog on the left side of the +

38 # operator is the object referenced by the "self" parameter. The

39 # "otherDog" parameter is the dog on the right side of the + operator.

40 def add (self,otherDog):

41 return Dog("Puppy of " + + " and " +,

42 self.month,, self.year + 1,

43 self.speakText + otherDog.speakText)


45 def main():

46 boyDog = Dog("Mesa", 5, 15, 2004, "WOOOOF")

47 girlDog = Dog("Sequoia", 5, 6, 2004, "barkbark")

48 print(boyDog.speak())

49 print(girlDog.speak())

50 print(boyDog.birthDate())

51 print(girlDog.birthDate())

52 boyDog.changeBark("woofywoofy")

53 print(boyDog.speak())

54 puppy = boyDog + girlDog

55 print(puppy.speak())

56 print(puppy.getName())

57 print(puppy.birthDate())


59 if name == " main ":

60 main()

This text uses operator overloading fairly extensively. There are many operators that are defined in Python. Python programmers often call these operators Magic Methods because a method automatically gets called when an operator is used in an expression. Many of the common operators are given in the table in Fig. 1.4 for your

Method Defintion



add (self,y)

contains (self,y)

eq (self,y)

ge (self,y)

getitem (self,y)

gt (self,y)

hash (self)

int (self)

iter (self)

le (self,y)

len (self)

lt (self,y)

mod (self,y)

mul (self,y)

ne (self,y)

neg (self)

repr (self)

setitem (self,i,y)

str (self)

sub (self,y)

x + y

y in x x == y x >= y x[y]

x > y hash(x) int(x)

for v in x x <= y len(x)

x < y x % y x * y x != y

-x repr(x)

x[i] = y


x y

The addition of two objects. The type of x determines which add operator is called.

When x is a collection you can test to see if y is in it. Returns True or False depending on the values of x and y. Returns True or False depending on the values of x and y. Returns the item at the yth position in x.

Returns True or False depending on the values of x and y. Returns an integral value for x.

Returns an integer representation of x. Returns an iterator object for the sequence x.

Returns True or False depending on the values of x and y. Returns the size of x where x has some length attribute. Returns True or False depending on the values of x and y. Returns the value of x modulo y. This is the remainder of x/y. Returns the product of x and y.

Returns True or False depending on the values of x and y. Returns the unary negation of x.

Returns a string version of x suitable to be evaluated by the eval


Sets the item at the ith position in x to y.

Return a string representation of x suitable for user-level interaction.

The difference of two objects.

Fig. 1.4 Python Operator Magic Methods

convenience. For each operator the magic method is given, how to call the operator is given, and a short description of it as well. In the table, self and x refer to the same object. The type of x determines which operator method is called in each case in the table.

The repr(x) and the str(x) operators deserve a little more explanation. Both operators return a string representation of x. The difference is that the str operator should return a string that is suitable for human interaction while the repr operator is called when a string representation is needed that can be evaluated. For instance, if we wanted to define these two operators on the Dog class, the repr method would return the string “Dog('Mesa', 5,15,2004, 'WOOOF')” while the str operator might return just the dog's name. The repr operator, when called, will treat the string as an expression that could later be evaluated by the eval function in Python whereas the str operator simply returns a string for an object.

Found a mistake? Please highlight the word and press Shift + Enter  
< Prev   CONTENTS   Next >
Business & Finance
Computer Science
Language & Literature
Political science