Python 3.x 如何继承numpy.float并强制使用非负数
我想从Python 3.x 如何继承numpy.float并强制使用非负数,python-3.x,numpy,oop,Python 3.x,Numpy,Oop,我想从numpy.float继承来创建一个cash类 class Cash(numpy.float): def __init__(self, amount, currency='$'): super().__init__() self.amount = amount self.currency = currency def __str__(self): return f"Cash({round(self.amou
numpy.float
继承来创建一个cash
类
class Cash(numpy.float):
def __init__(self, amount, currency='$'):
super().__init__()
self.amount = amount
self.currency = currency
def __str__(self):
return f"Cash({round(self.amount, 2)}{self.currency})"
在算术过程中,强制该类为非负类的最佳策略是什么?例如,此测试方法返回-2.0
,但我希望它引发ValueError
def test_sub1(self):
c1 = Cash(4.00)
c2 = Cash(6)
self.assertEqual(2, c1 - c2)
第一步是覆盖所有算术魔术函数,例如
\uuuuuu sub\uuuuu
或\uuuu add\uuuu
并引发错误第一步可能的重复是覆盖所有算术魔术函数,例如\uuuuu sub\uuuuu
或\uuuu add\uuuuu
并引发错误可能的重复