Python, how would I go about creating a money class that stores monetary values
ID: 3869621 • Letter: P
Question
Python, how would I go about creating a money class that stores monetary values in dollars and cents and that has instance variables for dollars and cents, uses and__init__ method, uses a __repr__ printing method and uses an __add__ that is passed another money object and adds that money data to self's money data and finally has three different getter methods that return a decimal conversion of money into that type (which for mine is yen, euro and the Canadian dollar) and get three different conversion rates which then is used to alter the money object when that method is called. Any and all help is greatly appreciated! If anyone needs additional information, then I will try my best to supply it.
Explanation / Answer
#!usr/python/bin
class Money:
def __init__(self, dollar, cents):
self.dollar = dollar;
self.cents = cents;
def __repr__(self):
print("$" + str(self.dollar) + "." + str(self.cents))
def __add__(self, obj):
self.dollar = self.dollar + obj.dollar
self.cents = self.cents + obj.cents
def getEuro(self):
value = self.dollar + self.cents/100
value = value * 0.84
return value
def getYen(self):
value = self.dollar + self.cents/100
value = value * 110.25
return value
def getCanadianDollar(self):
value = self.dollar + self.cents/100
value = value * 1.25
return value
m1 = Money(200,20)
m2 = Money(300,45)
m1.__repr__()
m2.__repr__()
m1.__add__(m2)
m1.__repr__()
print("(In Euro)",m2.getEuro())
print("(In Yen)",m2.getYen())
print("(In Canadian Dollar)",m2.getCanadianDollar())
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.