diff options
author | Tim Peters <tim.peters@gmail.com> | 2003-05-17 15:57:00 (GMT) |
---|---|---|
committer | Tim Peters <tim.peters@gmail.com> | 2003-05-17 15:57:00 (GMT) |
commit | b0c854d6a747cd64ff7b23b8e9f9ef93ff8ac0ac (patch) | |
tree | 367f74e70138c99155a965da3707f05d8095ecdc /Lib/test | |
parent | 108c40c74c5f3169b9095b464b3e868171571ff6 (diff) | |
download | cpython-b0c854d6a747cd64ff7b23b8e9f9ef93ff8ac0ac.zip cpython-b0c854d6a747cd64ff7b23b8e9f9ef93ff8ac0ac.tar.gz cpython-b0c854d6a747cd64ff7b23b8e9f9ef93ff8ac0ac.tar.bz2 |
datetime.timedelta is now subclassable in Python. The new test shows
one good use: a subclass adding a method to express the duration as
a number of hours (or minutes, or whatever else you want to add). The
native breakdown into days+seconds+us is often clumsy. Incidentally
moved a large chunk of object-initialization code closer to the top of
the file, to avoid worse forward-reference trickery.
Diffstat (limited to 'Lib/test')
-rw-r--r-- | Lib/test/test_datetime.py | 31 |
1 files changed, 31 insertions, 0 deletions
diff --git a/Lib/test/test_datetime.py b/Lib/test/test_datetime.py index c4978f3..cca0c9d 100644 --- a/Lib/test/test_datetime.py +++ b/Lib/test/test_datetime.py @@ -443,6 +443,37 @@ class TestTimeDelta(HarmlessMixedComparison): self.failUnless(timedelta(microseconds=1)) self.failUnless(not timedelta(0)) + def test_subclass_timedelta(self): + + class T(timedelta): + def from_td(td): + return T(td.days, td.seconds, td.microseconds) + from_td = staticmethod(from_td) + + def as_hours(self): + sum = (self.days * 24 + + self.seconds / 3600.0 + + self.microseconds / 3600e6) + return round(sum) + + t1 = T(days=1) + self.assert_(type(t1) is T) + self.assertEqual(t1.as_hours(), 24) + + t2 = T(days=-1, seconds=-3600) + self.assert_(type(t2) is T) + self.assertEqual(t2.as_hours(), -25) + + t3 = t1 + t2 + self.assert_(type(t3) is timedelta) + t4 = T.from_td(t3) + self.assert_(type(t4) is T) + self.assertEqual(t3.days, t4.days) + self.assertEqual(t3.seconds, t4.seconds) + self.assertEqual(t3.microseconds, t4.microseconds) + self.assertEqual(str(t3), str(t4)) + self.assertEqual(t4.as_hours(), -1) + ############################################################################# # date tests |