Inheriting class attribute with double underscore

前端 未结 2 419
暗喜
暗喜 2021-01-24 05:04

I think I understand the concept of \"name mangling\" in python, but there\'s something that I probably missed. Take a look at the following code:

#!/usr/bin/env         


        
2条回答
  •  不要未来只要你来
    2021-01-24 05:46

    As you have noticed, the name used for name mangling is the name of the class where a method is declared, not the derived type of the current object.

    The documentation for this feature explicitly gives an example about protecting a variable from a derived class (rather than from external code using an instance variable).

    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)
    

提交回复
热议问题