mirror of https://github.com/python/cpython
Issue 12086: add example showing how to use name mangling.
This commit is contained in:
parent
320b91495a
commit
fd1cb59618
|
@ -553,6 +553,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
|
without regard to the syntactic position of the identifier, as long as it
|
||||||
occurs within the definition of a class.
|
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
|
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
|
possible to access or modify a variable that is considered private. This can
|
||||||
even be useful in special circumstances, such as in the debugger.
|
even be useful in special circumstances, such as in the debugger.
|
||||||
|
|
Loading…
Reference in New Issue