Commit b8e0072f authored by Raymond Hettinger's avatar Raymond Hettinger

Add subclassing example to docs for named tuples.

parent 4273222a
...@@ -510,15 +510,22 @@ When casting a dictionary to a named tuple, use the double-star-operator [#]_:: ...@@ -510,15 +510,22 @@ When casting a dictionary to a named tuple, use the double-star-operator [#]_::
Point(x=11, y=22) Point(x=11, y=22)
Since a named tuple is a regular Python class, it is easy to add or change 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 functionality with a subclass. Here is how to add a calculated field and
the :meth:`__repr__` method: a custom fixed-width print format:
:: ::
>>> Point = namedtuple('Point', 'x y') >>> class Point(namedtuple('Point', 'x y')):
>>> Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self @property
>>> Point(x=11, y=22) def hypot(self):
Point(11.000, 22.000) 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 Default values can be implemented by starting with a prototype instance
and customizing it with :meth:`_replace`: and customizing it with :meth:`_replace`:
......
...@@ -116,8 +116,15 @@ if __name__ == '__main__': ...@@ -116,8 +116,15 @@ if __name__ == '__main__':
assert p == loads(dumps(p)) assert p == loads(dumps(p))
# test and demonstrate ability to override methods # test and demonstrate ability to override methods
Point.__repr__ = lambda self: 'Point(%.3f, %.3f)' % self class Point(namedtuple('Point', 'x y')):
print p @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 import doctest
TestResults = namedtuple('TestResults', 'failed attempted') TestResults = namedtuple('TestResults', 'failed attempted')
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment