Name mangling vs qualified access to class attributes
Cameron Simpson
cs at zip.com.au
Tue Dec 13 16:52:23 EST 2016
More information about the Python-list mailing list
Tue Dec 13 16:52:23 EST 2016
- Previous message (by thread): Name mangling vs qualified access to class attributes
- Next message (by thread): Name mangling vs qualified access to class attributes
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
On 13Dec2016 12:27, paolieri at gmail.com <paolieri at gmail.com> wrote: >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)'? IMO, mostly in that "Mapping.update" hardwires the class name, whereas "self.__update" will survive a class rename. I confess I've never used name mangling in the manner shown in the example. Hoping for more insightful comments... Cheers, Cameron Simpson <cs at zip.com.au>
- Previous message (by thread): Name mangling vs qualified access to class attributes
- 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