The code below is my current code
class Money(object):
def __init__(self, dollars=0, cents=0):
self.dollars = dollars + cents//100
self.cents = cents %100
def __radd__(self, other):
if isinstance(other, Money):
other = other.cents + other.dollars * 100
elif isinstance(other, int):
other = other * 100
elif isinstance(other, float):
other = int(other * 100)
money = int(other) + float(self.cents + self.dollars * 100)
self.dollars = money // 100
self.cents = money % 100
return "$%d.%2d" %(self.dollars,self.cents)
def money_text_2():
m1 = Money(3, 50)
m2 = Money(2, 60)
print(m1 == m2)
print(m1 + m2)
print(10 + m1 + m2)
money_text()
But it keeps getting this error:
money = int(other) + float(self.cents + self.dollars * 100)
ValueError: invalid literal for int() with base 10: '$16.10'
I spent the past 30 minutes trying to find a solution with no results
Can someone point it out for me?
I fix the ValueError and some other bugs, add more test cases.
$13.50
,which can't pass any if statement in your __radd__
method. So you got a ValueError in print(10 + m1 + m2)
, which you attempt to add a string to a Money class. I fix it to return a Money instance and __repr__
to display the format you want.__radd__
method, which can't pass test case like m1 + 10 + m2
.I add __ladd__
method to handle it.__add__
method. I add it to handle test case like m1 + m2
Money2
not defined error.code:
class Money(object):
def __init__(self, dollars=0, cents=0):
self.dollars = dollars + cents//100
self.cents = cents %100
def add_func(self,other):
if isinstance(other, Money):
other = other.cents + other.dollars * 100
elif isinstance(other, int):
other = other * 100
elif isinstance(other, float):
other = int(other * 100)
money = int(other) + float(self.cents + self.dollars * 100)
return Money(money // 100,money % 100)
def __add__(self, other):
return self.add_func(other)
def __ladd__(self,other):
return self.add_func(other)
def __radd__(self,other):
return self.add_func(other)
def __repr__(self):
return "$%d.%2d" %(self.dollars,self.cents)
def money_text():
m1 = Money(3, 50)
m2 = Money(2, 60)
print(m1 == m2)
print(m1 + m2)
print(m1 + 10 + m2)
print(10 + m1 + m2)
m3 = Money(1, 0)
m4 = Money(0, 99)
print(m3 + m4)
print(1.5 + m3 + m4)
money_text()
result:
False
$6.10
$16.10
$16.10
$1.99
$3.49