Introduction to Programming using Python 1st Edition

Published by Pearson
ISBN 10: 0132747189
ISBN 13: 978-0-13274-718-9

Chapter 8 - More on Strings and Special Methods - Section 8.5 - Operator Overloading and Special Methods - Check Point - MyProgrammingLab - Page 258: 8.10

Answer

In Python, the special methods that correspond to the operators +, -, *, /, %, ==, !=, <, <=, >, and >= are: __add__ for the + operator __sub__ for the - operator __mul__ for the * operator __truediv__ for the / operator (in Python 3) or __div__ for the / operator (in Python 2) __mod__ for the % operator __eq__ for the == operator __ne__ for the != operator __lt__ for the < operator __le__ for the <= operator __gt__ for the > operator __ge__ for the >= operator These special methods are also known as dunder methods (short for "double underscore"). By defining these special methods in your classes, you can customize the behavior of the corresponding operators when they are used with objects of your class.

Work Step by Step

Here's an example of how you might use the __add__ method to overload the + operator for a custom class: class Vector: $\hspace{4mm}$def __init__(self, x, y): $\hspace{8mm}$self.x = x $\hspace{8mm}$self.y = y $\hspace{4mm}$def __add__(self, other): $\hspace{8mm}$return Vector(self.x + other.x, self.y + other.y) v1 = Vector(1, 2) v2 = Vector(3, 4) v3 = v1 + v2 print(v3.x, v3.y) # Output: 4 6
Update this answer!

You can help us out by revising, improving and updating this answer.

Update this answer

After you claim an answer you’ll have 24 hours to send in a draft. An editor will review the submission and either publish your submission or provide feedback.