[英]I keep getting an error called 'int' object has no attribute 'replace'
[英]I keep getting an attribute error 'int' object has no attribute 'dollars'
我在这个Money类上工作,直到乘法为止,一切正常。 我不断收到属性错误,无法弄清楚我要去哪里。 乘法是float类型的。
class Money:
def __init__(self, d, c):
self.dollars = d
self.cents = c
def __str__(self):
return '${}.{:02d}'.format(self.dollars, self.cents)
def __repr__(self):
return 'Money({},{})'.format(repr(self.dollars), self.cents)
def add(self, other):
d = self.dollars + other.dollars
c = self.cents + other.cents
while c > 99:
d += 1
c -= 100
return Money(d,c)
def subtract(self, other):
d = self.dollars - other.dollars
c = self.cents - other.cents
while c < 0:
d -= 1
c += 100
return Money(d,c)
def times(self, mult):
d = self.dollars * mult.dollars
c = self.cents * mult.cents
while c > 99:
d *= 1
c *= 100
return Money(d,c)
>>> m2 = Money(10,10)
>>> m2.times(3)
Traceback (most recent call last): File "<pyshell#51>", line 1, in <module> m2.times(3)
File "/Users/kylerbolden/Desktop/hw2.py", line 67, in times
d = float(self.dollars) * float(mult.dollars)
AttributeError: 'int' object has no attribute 'dollars'
在m2.times(3)
,您将int
3
传递给times
方法。 但是,在times方法中,您尝试乘以mult.dollars
,而不是实际传递的dollars
( 3
)。
mult.dollars
不起作用像self.dollars
会。 实际上,它根本不是有效的构造。
尝试
>>> class Money:
... def __init__(self, d, c):
... self.dollars = d
... self.cents = c
... def times(self, mult):
... d = self.dollars * mult
... c = self.cents * mult
... while c > 99:
... d *= 1
... c *= 100
... return Money(d, c)
显然,您还必须修改其余的代码。
似乎您想返回一个新的Money
对象,而不是使用这些方法中的每种方法来实现平衡,但只是为了证明我在上文中提到的观点:
>>> class Money:
... def __init__(self, d, c):
... self.dollars = d
... self.cents = c
... def times(self, mult):
... d = self.dollars * mult
... c = self.cents * mult
... while c > 99:
... d *= 1
... c *= 100
... return (d,c)
...
>>> m2 = Money(10, 10)
>>> m2.times(3)
(30, 30)
编辑:好的,以上似乎不是您想要的内容,但是我将其留给遇到类似错误的人。 您需要在代码中修复的是您试图传递的mult
对象。 您的add
和subtract
都具有相同的参数: self
和other
,我想其中other
是Money
类的另一个实例。 因此,您基本上是在尝试乘,加或减不同的余额? 在这种情况下,改变mult.dollars
和mult.cents
到other.dollars
和other.cents
,这样就可以再访问这些属性Money
对象。
更改后:
>>> class Money:
... def __init__(self, d, c):
... self.dollars = d
... self.cents = c
... def times(self, other):
... d = self.dollars * other.dollars
... c = self.cents * other.cents
... while c > 99:
... d *= 1
... c *= 100
... return Money(d,c)
...
>>> m2 = Money(2, 3)
>>> m3 = Money(4, 5)
>>> m2.times(m3)
Money(8,15)
另外,您可能需要查看d *= 1
和c *= 100
行,但这应该可以回答您的最初问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.