Dsaa 25
Dsaa 25
5 Operator Overloading 9
44 def main():
45 boyDog = Dog("Mesa", 5, 15, 2004, "WOOOOF")
46 girlDog = Dog("Sequoia", 5, 6, 2004, "barkbark")
47 print(boyDog.speak())
48 print(girlDog.speak())
49 print(boyDog.birthDate())
50 print(girlDog.birthDate())
51 boyDog.changeBark("woofywoofy")
52 print(boyDog.speak())
53 puppy = boyDog + girlDog
54 print(puppy.speak())
55 print(puppy.getName())
56 print(puppy.birthDate())
57
58 if __name__ == "__main__":
59 main()
Listing 1.7 Operator Overloading for the Dog Class
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
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.