Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 6ddefd7

Browse files
committed
Issue 12086: add example showing how to use name mangling.
1 parent 9d3df6d commit 6ddefd7

1 file changed

Lines changed: 22 additions & 0 deletions

File tree

Doc/tutorial/classes.rst

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,28 @@ current class name with leading underscore(s) stripped. This mangling is done
595595
without regard to the syntactic position of the identifier, as long as it
596596
occurs within the definition of a class.
597597

598+
Name mangling is helpful for letting subclasses override methods without
599+
breaking intraclass method calls. For example::
600+
601+
class Mapping:
602+
def __init__(self, iterable):
603+
self.items_list = []
604+
self.__update(iterable)
605+
606+
def update(self, iterable):
607+
for item in iterable:
608+
self.items_list.append(item)
609+
610+
__update = update # private copy of original update() method
611+
612+
class MappingSubclass(Mapping):
613+
614+
def update(self, keys, values):
615+
# provides new signature for update()
616+
# but does not break __init__()
617+
for item in zip(keys, values):
618+
self.items_list.append(item)
619+
598620
Note that the mangling rules are designed mostly to avoid accidents; it still is
599621
possible to access or modify a variable that is considered private. This can
600622
even be useful in special circumstances, such as in the debugger.

0 commit comments

Comments
 (0)