fix for cmp and add, sub

This commit is contained in:
James Turk 2015-03-24 00:07:01 -04:00
parent 8e76a5c3ef
commit d6096b9ed2
2 changed files with 10 additions and 4 deletions

View File

@ -30,9 +30,14 @@ def test_basic_cmp():
def test_conversion_cmp():
assert Mass(1, 'kg') < Mass(100, 'lb')
assert Mass(10000000, 'g') > Mass(100, 'lb')
assert Mass(1000000, 'g') > Mass(100, 'lb')
def test_add_sub():
def test_addition():
assert Mass(1, 'kg') + Mass(2, 'kg') == Mass(3, 'kg')
assert Mass(1, 'kg') + Mass(1, 'lb') > Mass(1.4, 'kg')
def test_subtraction():
assert Mass(2, 'kg') - Mass(1, 'kg') == Mass(1, 'kg')
assert Mass(1, 'kg') - Mass(1, 'lb') < Mass(0.55, 'kg')

View File

@ -13,7 +13,7 @@ class Unit(object):
_mapping = {}
def __init__(self, n, unit):
self.scalar = n
self.scalar = float(n)
if unit not in self._mapping:
raise ValueError('invalid unit {} for {}'.format(unit, self.__class__.__name__))
self.unit = unit
@ -41,7 +41,8 @@ class Unit(object):
def __cmp__(self, other):
if self.unit != other.unit:
other = other.as_unit(self.unit)
return self.scalar - other.scalar
# cmp() removed in Python 3, recommended to replace with this
return (self.scalar > other.scalar) - (self.scalar < other.scalar)
def __add__(self, other):
if self.unit != other.unit: