Python name mangling

后端 未结 11 2137
天命终不由人
天命终不由人 2020-11-22 05:31

In other languages, a general guideline that helps produce better code is always make everything as hidden as possible. If in doubt about whether a variable should be privat

11条回答
  •  广开言路
    2020-11-22 06:08

    Following code snippet will explain all different cases :

    • two leading underscores (__a)
    • single leading underscore (_a)
    • no underscore (a)

      class Test:
      
      def __init__(self):
          self.__a = 'test1'
          self._a = 'test2'
          self.a = 'test3'
      
      def change_value(self,value):
          self.__a = value
          return self.__a
      

    printing all valid attributes of Test Object

    testObj1 = Test()
    valid_attributes = dir(testObj1)
    print valid_attributes
    
    ['_Test__a', '__doc__', '__init__', '__module__', '_a', 'a', 
    'change_value']
    

    Here, you can see that name of __a has been changed to _Test__a to prevent this variable to be overridden by any of the subclass. This concept is known as "Name Mangling" in python. You can access this like this :

    testObj2 = Test()
    print testObj2._Test__a
    
    test1
    

    Similarly, in case of _a, the variable is just to notify the developer that it should be used as internal variable of that class, the python interpreter won't do anything even if you access it, but it is not a good practise.

    testObj3 = Test()
    print testObj3._a
    
    test2
    

    a variable can be accesses from anywhere it's like a public class variable.

    testObj4 = Test()
    print testObj4.a
    
    test3
    

    Hope the answer helped you :)

提交回复
热议问题