我不断收到属性错误' int'对象没有属性'美元'

时间:2016-10-06 01:22:09

标签: python class attributes

我正在研究这个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'

1 个答案:

答案 0 :(得分:3)

m2.times(3)中,您将int 3传递给times方法。但是,在时间方法中,您尝试乘以mult.dollars,而不是乘以实际传递的dollars3)。

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对象。您的addsubtract方法都具有相同的参数:selfother,其中otherMoney类的另一个实例,I假设。那么,你基本上是在试图增加,增加或减少不同的余额吗?在这种情况下,请将mult.dollarsmult.cents更改为other.dollarsother.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 *= 1c *= 100行,但这应该回答您的初始问题。