mirror of
https://github.com/python/cpython.git
synced 2025-12-04 08:34:25 +00:00
Add another named tuple subclassing example.
This commit is contained in:
parent
fd1c24518b
commit
dc55f35f38
2 changed files with 16 additions and 0 deletions
|
|
@ -527,6 +527,14 @@ a fixed-width print format:
|
||||||
Point(x=2.000, y=5.000, hypot=5.385)
|
Point(x=2.000, y=5.000, hypot=5.385)
|
||||||
Point(x=1.286, y=6.000, hypot=6.136)
|
Point(x=1.286, y=6.000, hypot=6.136)
|
||||||
|
|
||||||
|
Another use for subclassing is to replace performance critcal methods with
|
||||||
|
faster versions that bypass error-checking and localize variable access:
|
||||||
|
|
||||||
|
>>> class Point(namedtuple('Point', 'x y')):
|
||||||
|
_make = classmethod(tuple.__new__)
|
||||||
|
def _replace(self, _map=map, **kwds):
|
||||||
|
return self._make(_map(kwds.pop, ('x', 'y'), self))
|
||||||
|
|
||||||
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`:
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -125,6 +125,14 @@ if __name__ == '__main__':
|
||||||
|
|
||||||
print Point(3, 4),'\n', Point(2, 5), '\n', Point(9./7, 6)
|
print Point(3, 4),'\n', Point(2, 5), '\n', Point(9./7, 6)
|
||||||
|
|
||||||
|
class Point(namedtuple('Point', 'x y')):
|
||||||
|
'Point class with optimized _make() and _replace() without error-checking'
|
||||||
|
_make = classmethod(tuple.__new__)
|
||||||
|
def _replace(self, _map=map, **kwds):
|
||||||
|
return self._make(_map(kwds.pop, ('x', 'y'), self))
|
||||||
|
|
||||||
|
print Point(11, 22)._replace(x=100)
|
||||||
|
|
||||||
import doctest
|
import doctest
|
||||||
TestResults = namedtuple('TestResults', 'failed attempted')
|
TestResults = namedtuple('TestResults', 'failed attempted')
|
||||||
print TestResults(*doctest.testmod())
|
print TestResults(*doctest.testmod())
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue