Last active
August 12, 2018 14:19
-
-
Save santosh/2a81e5537b4c92c23482bc1b89f791fc to your computer and use it in GitHub Desktop.
Operator overloading in Python.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # In this script, we'll overload '+' operator to add two classes. | |
| class CurrenciesDoNotMatchError(TypeError): | |
| def __init__(self, message): | |
| super().__init__(message) | |
| class Currency: | |
| def __init__(self, currency, amount): | |
| self.currency = currency | |
| self.amount = amount | |
| def __repr__(self): | |
| return repr((self.currency, self.amount)) | |
| def __add__(self, other): | |
| if self.currency != other.currency: | |
| raise CurrenciesDoNotMatchError(self.currency + " " + other.currency) | |
| total_amount = self.amount + other.amount | |
| return Currency(self.currency, total_amount) | |
| value1 = Currency("USD", 20) | |
| value2 = Currency("USD", 30) | |
| print(value1 + value2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment