Skip to content

Instantly share code, notes, and snippets.

@santosh
Last active August 12, 2018 14:19
Show Gist options
  • Save santosh/2a81e5537b4c92c23482bc1b89f791fc to your computer and use it in GitHub Desktop.
Save santosh/2a81e5537b4c92c23482bc1b89f791fc to your computer and use it in GitHub Desktop.
Operator overloading in Python.
# 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