diff options
author | Raymond Hettinger <python@rcn.com> | 2011-06-25 14:31:06 (GMT) |
---|---|---|
committer | Raymond Hettinger <python@rcn.com> | 2011-06-25 14:31:06 (GMT) |
commit | 142d0f5e5a11339d74c105668fe394b2d90e20d6 (patch) | |
tree | 712509b229f479f1d230b67d8b13e2e4c4d4fa84 /Doc/tutorial | |
parent | 06eef9c1306e8cf44bbacaa81fcff6b0c2e3d744 (diff) | |
parent | 6ddefd791600312a443d31c128536eca81d801ea (diff) | |
download | cpython-142d0f5e5a11339d74c105668fe394b2d90e20d6.zip cpython-142d0f5e5a11339d74c105668fe394b2d90e20d6.tar.gz cpython-142d0f5e5a11339d74c105668fe394b2d90e20d6.tar.bz2 |
Issue 12086: add example showing how to use name mangling.
Diffstat (limited to 'Doc/tutorial')
-rw-r--r-- | Doc/tutorial/classes.rst | 22 |
1 files changed, 22 insertions, 0 deletions
diff --git a/Doc/tutorial/classes.rst b/Doc/tutorial/classes.rst index 3e547a5..336d074 100644 --- a/Doc/tutorial/classes.rst +++ b/Doc/tutorial/classes.rst @@ -595,6 +595,28 @@ current class name with leading underscore(s) stripped. This mangling is done 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. |