[Python-checkins] r59807 - in python/trunk: Doc/library/collections.rst Lib/collections.py
raymond.hettinger
python-checkins at python.org
Mon Jan 7 05:24:49 CET 2008
Author: raymond.hettinger
Date: Mon Jan 7 05:24:49 2008
New Revision: 59807
Modified:
python/trunk/Doc/library/collections.rst
python/trunk/Lib/collections.py
Log:
Add subclassing example to docs for named tuples.
Modified: python/trunk/Doc/library/collections.rst
==============================================================================
--- python/trunk/Doc/library/collections.rst (original)
+++ python/trunk/Doc/library/collections.rst Mon Jan 7 05:24:49 2008
@@ -510,15 +510,22 @@
Point(x=11, y=22)
Since a named tuple is a regular Python class, it is easy to add or change
-functionality. For example, the display format can be changed by overriding
-the :meth:`__repr__` method:
+functionality with a subclass. Here is how to add a calculated field and
+a custom fixed-width print format:
::
- >>> Point = namedtuple('Point', 'x y')
- >>> Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
- >>> Point(x=11, y=22)
- Point(11.000, 22.000)
+ >>> class Point(namedtuple('Point', 'x y')):
+ @property
+ def hypot(self):
+ return (self.x ** 2 + self.y ** 2) ** 0.5
+ def __repr__(self):
+ return 'Point(x=%.3f, y=%.3f, hypot=%.3f)' % (self.x, self.y, self.hypot)
+
+ >>> print Point(3, 4)
+ Point(x=3.000, y=4.000, hypot=5.000)
+ >>> Point(2, 5)
+ Point(x=2.000, y=5.000, hypot=5.385)
Default values can be implemented by starting with a prototype instance
and customizing it with :meth:`_replace`:
Modified: python/trunk/Lib/collections.py
==============================================================================
--- python/trunk/Lib/collections.py (original)
+++ python/trunk/Lib/collections.py Mon Jan 7 05:24:49 2008
@@ -116,8 +116,15 @@
assert p == loads(dumps(p))
# test and demonstrate ability to override methods
- Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self
- print p
+ class Point(namedtuple('Point', 'x y')):
+ @property
+ def hypot(self):
+ return (self.x ** 2 + self.y ** 2) ** 0.5
+ def __repr__(self):
+ return 'Point(x=%.3f, y=%.3f, hypot=%.3f)' % (self.x, self.y, self.hypot)
+
+ print Point(3, 4)
+ print Point(2, 5)
import doctest
TestResults = namedtuple('TestResults', 'failed attempted')
More information about the Python-checkins
mailing list