不支持 * : ‘ float’和‘ Decimal’的操作数类型

我只是在学习类函数等等,所以我决定创建一个简单的函数什么应该给我税额。

到目前为止这是我的代码。

class VAT_calculator:
"""
A set of methods for VAT calculations.
"""


def __init__(self, amount=None):
self.amount = amount
self.VAT = decimal.Decimal('0.095')


def initialize(self):
self.amount = 0


def total_with_VAT(self):
"""
Returns amount with VAT added.
"""
if not self.amount:
msg = u"Cannot add VAT if no amount is passed!'"
raise ValidationError(msg)


return (self.amount * self.VAT).quantize(self.amount, rounding=decimal.ROUND_UP)

我的问题是我得到了下面的错误:

不支持 * : ‘ float’和‘ Decimal’* * 的操作数类型

我不明白为什么这样不行!

147259 次浏览

It seems like self.VAT is of decimal.Decimal type and self.amount is a float, thing that you can't do.

Try decimal.Decimal(self.amount) * self.VAT instead.

Your issue is, as the error says, that you're trying to multiply a Decimal by a float

The simplest solution is to rewrite any reference to amount declaring it as a Decimal object:

self.amount = decimal.Decimal(float(amount))

and in initialize:

self.amount = decimal.Decimal('0.0')

Another option would be to declare Decimals in your final line:

return (decimal.Decimal(float(self.amount)) * self.VAT).quantize(decimal.Decimal(float(self.amount)), rounding=decimal.ROUND_UP)

...but that seems messier.