[英]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.