Name mangling vs qualified access to class attributes
paolieri at gmail.com
paolieri at gmail.com
Tue Dec 13 15:27:26 EST 2016
More information about the Python-list mailing list
Tue Dec 13 15:27:26 EST 2016
- Previous message (by thread): Splitting text into lines
- Next message (by thread): Name mangling vs qualified access to class attributes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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? Best, -- Marco
- Previous message (by thread): Splitting text into lines
- Next message (by thread): Name mangling vs qualified access to class attributes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
More information about the Python-list mailing list