Money和TypeError:__ init __()取1到2个位置参数,但给出了3个

时间:2016-05-14 16:49:21

标签: python python-3.x

Python新手在这里。我在Eclipse上使用PyDev。

我正在编写一个程序来处理我的银行交易。我使用Money包(1.3.0)。该程序运行良好,直到我了解到您可以创建Money的货币预设变体(如on this page所示。

当我使用Money时,以下剪辑工作正常,但是当我使用我的美元预设时它会出错:

from money import Money
class USD(Money):
    def __init__(self, amount='0'):
        super().__init__(amount=amount, currency='USD')
a = Money(0,'USD')
b = Money(-360,'USD')
a += b
print(a)
c = USD(0)
d = USD(-360)
c += d
print(c)

(print()语句的真正目的是设置断点的方便位置。)

我收到此错误:

File "D:\Dev\mymoney\mymoney.py", line 11, in <module>
  c += d
File "C:\Program Files\Python35\lib\site-packages\money\money.py", line 119, in __add__
   return self.__class__(amount, self._currency)
TypeError: __init__() takes from 1 to 2 positional arguments but 3 were given

我想知道如何修复我的代码以使其正常工作,但我需要了解问题所在。对于后者,无论是您的解释还是指向我可以学习的文档中某些内容的指针都会有所帮助。

1 个答案:

答案 0 :(得分:1)

这是因为在source code here中定义的__add__方法中,会返回一个新类,将amount self._currency传递给{ {1}}。

__init__

但您的货币预设子类仅消耗金额,而不是货币。因此,你传递了太多的位置参数。

您的选择是不要将def __add__(self, other): if isinstance(other, Money): if other.currency != self._currency: raise CurrencyMismatch(self._currency, other.currency, '+') other = other.amount amount = self._amount + other return self.__class__(amount, self._currency) 作为货币预设的子类(我的建议,我不太重视),更改子类的Money方法以接受默认值参数设置为该子类的相应货币,或覆盖__init__之类的方法,以通过类似__add__之类的方式将货币参数传递给__init__。但是,不要做后者,这不是必要的。