Skip to content
Projects
Groups
Snippets
Help
Loading...
Help
Support
Keyboard shortcuts
?
Submit feedback
Contribute to GitLab
Sign in / Register
Toggle navigation
C
cpython
Project overview
Project overview
Details
Activity
Releases
Repository
Repository
Files
Commits
Branches
Tags
Contributors
Graph
Compare
Issues
0
Issues
0
List
Boards
Labels
Milestones
Merge Requests
0
Merge Requests
0
Analytics
Analytics
Repository
Value Stream
Wiki
Wiki
Members
Members
Collapse sidebar
Close sidebar
Activity
Graph
Create a new issue
Commits
Issue Boards
Open sidebar
Kirill Smelkov
cpython
Commits
dc55f35f
Commit
dc55f35f
authored
Jan 07, 2008
by
Raymond Hettinger
Browse files
Options
Browse Files
Download
Email Patches
Plain Diff
Add another named tuple subclassing example.
parent
fd1c2451
Changes
2
Hide whitespace changes
Inline
Side-by-side
Showing
2 changed files
with
16 additions
and
0 deletions
+16
-0
Doc/library/collections.rst
Doc/library/collections.rst
+8
-0
Lib/collections.py
Lib/collections.py
+8
-0
No files found.
Doc/library/collections.rst
View file @
dc55f35f
...
...
@@ -527,6 +527,14 @@ a fixed-width print format:
Point(x=2.000, y=5.000, hypot=5.385)
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
and customizing it with :meth:`_replace`:
...
...
Lib/collections.py
View file @
dc55f35f
...
...
@@ -125,6 +125,14 @@ if __name__ == '__main__':
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
TestResults
=
namedtuple
(
'TestResults'
,
'failed attempted'
)
print
TestResults
(
*
doctest
.
testmod
())
Write
Preview
Markdown
is supported
0%
Try again
or
attach a new file
Attach a file
Cancel
You are about to add
0
people
to the discussion. Proceed with caution.
Finish editing this message first!
Cancel
Please
register
or
sign in
to comment