| 2004 | } |
| 2005 | |
| 2006 | class Amount: |
| 2007 | def __init__(self, amount, currency): |
| 2008 | self.currency = currency |
| 2009 | self.amount = amount |
| 2010 | |
| 2011 | def __add__(self, other): |
| 2012 | return Amount( |
| 2013 | self.amount + other.as_currency(self.currency).amount, |
| 2014 | self.currency, |
| 2015 | ) |
| 2016 | |
| 2017 | def __sub__(self, other): |
| 2018 | return Amount( |
| 2019 | self.amount - other.as_currency(self.currency).amount, |
| 2020 | self.currency, |
| 2021 | ) |
| 2022 | |
| 2023 | def __lt__(self, other): |
| 2024 | return self.amount < other.as_currency(self.currency).amount |
| 2025 | |
| 2026 | def __gt__(self, other): |
| 2027 | return self.amount > other.as_currency(self.currency).amount |
| 2028 | |
| 2029 | def __eq__(self, other): |
| 2030 | return self.amount == other.as_currency(self.currency).amount |
| 2031 | |
| 2032 | def as_currency(self, other_currency): |
| 2033 | return Amount( |
| 2034 | currency_lookup[(self.currency, other_currency)] |
| 2035 | * self.amount, |
| 2036 | other_currency, |
| 2037 | ) |
| 2038 | |
| 2039 | def __clause_element__(self): |
| 2040 | # helper method for SQLAlchemy to interpret |
| 2041 | # the Amount object as a SQL element |
| 2042 | if isinstance(self.amount, (float, int, Decimal)): |
| 2043 | return literal(self.amount) |
| 2044 | else: |
| 2045 | return self.amount |
| 2046 | |
| 2047 | def __str__(self): |
| 2048 | return "%2.4f %s" % (self.amount, self.currency) |
| 2049 | |
| 2050 | def __repr__(self): |
| 2051 | return "Amount(%r, %r)" % (self.amount, self.currency) |
| 2052 | |
| 2053 | Base = declarative_base() |
| 2054 |
no outgoing calls