Name mangling vs qualified access to class attributes
dieter
dieter at handshake.de
Wed Dec 14 03:14:27 EST 2016
paolieri at gmail.com writes:
> The official Python tutorial at
>
> https://docs.python.org/3/tutorial/classes.html#private-variables
>
> says that "name mangling is helpful for letting subclasses override methods without breaking intraclass method calls" and makes an interesting 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)
>
>
> It seems to me that, in this example, one could just have:
>
> class Mapping:
> def __init__(self, iterable):
> self.items_list = []
> Mapping.update(self, iterable)
>
> def update(self, iterable):
> for item in iterable:
> self.items_list.append(item)
>
> and avoid copying 'Mapping.update' into 'Mapping.__update'. More generally, any time one needs to "let subclasses override methods without breaking intraclass method calls" (the goal stated in the tutorial), using qualified access to class attributes/methods should suffice.
>
> Am I missing something? Is 'self.__update(iterable)' in 'Mapping.__init__' preferable to 'Mapping.update(self, iterable)'?
>
> I think that, instead, name mangling is helpful to avoid accidental overrides of methods/attributes by the *current* class (rather than its subclasses). Given the way that C3 linearization works, you can't know in advance who will follow your class A in B.__mro__ when B extends A. Name mangling allows you to avoid overriding methods/attributes of classes that might follow.
>
> Any thoughts?
You can do that indeed for class level attributes (such as methods);
you cannot do it for instance level attributes (e.g. holding instance specific
values).
>From my point of view, "__" name mangling is particularly interesting
for mixin classes (i.e. classes implementing a single feature
and being designed to be used in deriving classes combining the necessary
features by deriving from all features classes required).
Those classes are typically combined with other classes - with a
corresponding risk of name clashes. Therefore, the above name mangling
is helpful to reduce that risk for private attributes (whether methods
or data attributes).
More information about the Python-list
mailing list