Page 353 - Beginning Programming with Pyth - John Paul Mueller
P. 353

 FIGURE 15-12: The code can process any number of entries in the list.
Overloading operators
In some situations, you want to be able to do something special as the result of using a standard operator such as add (+). In fact, sometimes Python doesn’t provide a default behavior for operators because it has no default to implement. No matter what the reason might be, overloading operators makes it possible to assign new functionality to existing operators so that they do what you want, rather than what Python intended. The following steps demonstrate how to overload an operator and use it as part of an application.
1. Type the following code into the Notebook — pressing Enter after
each line:
class MyClass:
def __init__(self, *args):
self.Input = args
def __add__(self, Other):
Output = MyClass()
Output.Input = self.Input + Other.Input return Output
def __str__(self): Output = ""
for Item in self.Input: Output += Item Output += " "
                       return Output
                 Value1 = MyClass("Red", "Green", "Blue")
                 Value2 = MyClass("Yellow", "Purple", "Cyan")
 


















































































   351   352   353   354   355