How to Write a Custom Class In Python

0
137

Python Assignment Help

OK, this is an example of a class that implements overloaded operators to appear as built in type. We’ll define a currency class that allows you to store the type of currency and can convert between different currencies. This is a simple example of the type of Python assignment help we can offer.

Here is the skeletal class will be extending, it has 2 currencies, feel free to add more.

from decimal import Decimal

_CURRENCIES = {“USD”: “${:.2f}”,

“GBP”: \u00a3{:.2f}”}

class Currency():

def __init__(self, amount = 0, currency = “GBP”):

self.amount = Decimal(amount)

self.currency = currency

def __str__(self):

return _CURRENCIES.get(self.currency).format(self.amount)

def main():

price = Currency(16.75)

print(price)

if __name__ == “__main__”:

main()

This code creates a cost object and displays it, to make it useful we want to be able to add currencies together and to multiply the price by an amount.

We want to allow the following.

def main():

price = Currency(16.75)

cost = price * 5

taxes = cost * 0.20

total = cost + taxes

print(total)

If you run the code you will get an error message.

Traceback (most recent call last):
File “C:/course/social/Currency.py”, line 24, in <module>
main()
File “C:/course/social/Currency.py”, line 17, in main
cost = price * 5
TypeError: unsupported operand type(s) for *: ‘Currency’ and ‘int’

So we need to allow the multiply and the add. So add the following code to the class.

def __mul__(self, other):

return Currency(self.amount * Decimal(other), self.currency)

def __add__(self, other):

return Currency(self.amount + other.amount)

And that works perfectly, lets extend it so that we can convert between currencies, add the following.

print(total)

dollars = total.to(“USD”)

pounds = dollars.to(“GBP”)

print(dollars, pounds)

def to(self, currency):

if self.currency == currency:

return self

return Currency(self.amount * _RATES[self.currency, currency], currency)

_RATES = {(“USD”, “GBP”) : Decimal(1/1.3),

(“GBP”, “USD”) : Decimal(1.3)}

This allows you to convert rates on the fly, so the one thing we have remaining would be to add pounds and dollars together. If you try it at the moment, the total will be incorrect since it won’t take the rate into account.

incorrect = dollars + pounds

print(incorrect)

£231.15

So we need to change the add method, so that if the currencies are not the same, it uses the first currency as the currency to use.

def __add__(self, other):

if self.currency == other.currency:

return Currency(self.amount + other.amount, self.currency)

return Currency(self.amount + other.to(self.currency).amount, self.currency)

Now the output is $261.30 which is correct. We could add further changes, but this at least illustrates the mathematics operators. We might want to implement the comparisons so we can sort, and so we will add that.

prices = [Currency(10), Currency(5), Currency(20)]

print(sorted(prices))

This gives an error TypeError: unorderable types: Currency() < Currency(), so lets add that.

def __lt__(self, other):

return self.amount < other.amount

def __repr__(self):

return str(self)

The repr is so that print [] works correctly.

This could be extended further to update the currency rates automatically each day, Python homework help could extend this for you if you wish. Look at the site on a regular basis for more example projects.

This code is presented by and copyright Programming Assignment Experts but license is granted to extend and use in any project as long as this message is included.

LEAVE A REPLY

Please enter your comment!
Please enter your name here