some basic math operators

This commit is contained in:
James Turk 2015-03-23 23:45:53 -04:00
parent 94af033fcd
commit 8e76a5c3ef
2 changed files with 34 additions and 2 deletions

View File

@ -16,3 +16,23 @@ def test_basic_conversions():
assert g.unit == 'g'
assert g.as_unit('lb').scalar == a.as_unit('lb').scalar
def test_basic_cmp():
assert Mass(1, 'kg') < Mass(2, 'kg')
assert Mass(1, 'kg') <= Mass(2, 'kg')
assert Mass(2, 'kg') <= Mass(2, 'kg')
assert Mass(2, 'kg') == Mass(2, 'kg')
assert Mass(2, 'kg') >= Mass(2, 'kg')
assert Mass(2, 'kg') > Mass(1, 'kg')
assert Mass(2, 'kg') >= Mass(1, 'kg')
def test_conversion_cmp():
assert Mass(1, 'kg') < Mass(100, 'lb')
assert Mass(10000000, 'g') > Mass(100, 'lb')
def test_add_sub():
assert Mass(1, 'kg') + Mass(2, 'kg') == Mass(3, 'kg')
assert Mass(2, 'kg') - Mass(1, 'kg') == Mass(1, 'kg')

View File

@ -38,8 +38,20 @@ class Unit(object):
def __repr__(self):
return 'U({}, {!r})'.format(self.scalar, self.unit)
def __cmp__(self):
pass
def __cmp__(self, other):
if self.unit != other.unit:
other = other.as_unit(self.unit)
return self.scalar - other.scalar
def __add__(self, other):
if self.unit != other.unit:
other = other.as_unit(self.unit)
return self.__class__(self.scalar.__add__(other.scalar), self.unit)
def __sub__(self, other):
if self.unit != other.unit:
other = other.as_unit(self.unit)
return self.__class__(self.scalar.__sub__(other.scalar), self.unit)
class Mass(Unit):