On 13Dec2016 12:27, paoli...@gmail.com <paoli...@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 <c...@zip.com.au>
--
https://mail.python.org/mailman/listinfo/python-list