下面的代码是我当前的代码
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()
但它不断收到此错误:
money = int(other) + float(self.cents + self.dollars * 100)
ValueError: invalid literal for int() with base 10: '$16.10'
过去 30 分钟我一直在寻找一个没有结果的解决方案
谁能帮我指点一下?
答案 0 :(得分:1)
我修复了 ValueError 和其他一些错误,添加了更多测试用例。
$13.50
这样的字符串,它不能在你的 __radd__
方法中传递任何 if 语句。因此,您在 print(10 + m1 + m2)
中遇到了 ValueError,您尝试向 Money 类添加字符串。我修复了它以返回一个 Money 实例和 __repr__
以显示您想要的格式。__radd__
方法,无法通过 m1 + 10 + m2
这样的测试用例。我添加了 __ladd__
方法来处理它。__add__
方法。我添加它来处理像 m1 + m2
Money2
未定义错误。代码:
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()
结果:
False
$6.10
$16.10
$16.10
$1.99
$3.49