[Python-checkins] cpython (2.7): Issue 12086: add example showing how to use name mangling.

raymond.hettinger python-checkins at python.org
Sat Jun 25 16:28:22 CEST 2011


http://hg.python.org/cpython/rev/68bc3c5960a4
changeset:   70973:68bc3c5960a4
branch:      2.7
parent:      70968:0ca8ffffd90b
user:        Raymond Hettinger <python at rcn.com>
date:        Sat Jun 25 16:28:07 2011 +0200
summary:
  Issue 12086: add example showing how to use name mangling.

files:
  Doc/tutorial/classes.rst |  22 ++++++++++++++++++++++
  1 files changed, 22 insertions(+), 0 deletions(-)


diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst
--- a/Doc/tutorial/classes.rst
+++ b/Doc/tutorial/classes.rst
@@ -553,6 +553,28 @@
 without regard to the syntactic position of the identifier, as long as it
 occurs within the definition of a class.
 
+Name mangling is helpful for letting subclasses override methods without
+breaking intraclass method calls.  For example::
+
+    class Mapping:
+        def __init__(self, iterable):
+            self.items_list = []
+            self.__update(iterable)
+
+        def update(self, iterable):
+            for item in iterable:
+                self.items_list.append(item)
+
+        __update = update   # private copy of original update() method
+
+    class MappingSubclass(Mapping):
+
+        def update(self, keys, values):
+            # provides new signature for update()
+            # but does not break __init__()
+            for item in zip(keys, values):
+                self.items_list.append(item)
+
 Note that the mangling rules are designed mostly to avoid accidents; it still is
 possible to access or modify a variable that is considered private.  This can
 even be useful in special circumstances, such as in the debugger.

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list