Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Well it is not intergrated in the language like i.e Java or C#. But Python does have the naming convention to mark vars that should not be touched with __ [0]

[0] https://docs.python.org/2/tutorial/classes.html#private-vari...



You and the article author both didn't seem to read that link.

A single leading underscore is a convention to mark a variable as private.

A double leading underscore "name mangles" the variable (adds the class to the name of the variable) and has a specific use case for inheritance. They're class level private, which is probably not what you want.

    class Number:
        def __init__(self, n):
            self._number = n
            self.__number = n
    
    
    class NumberChild(Number):
        def one_higher(self):
            return self._number + 1
    
        def two_higher(self):
            return self.__number + 2
    
    
    number_child = NumberChild(10)
    number_child.one_higher()  # This works
    number_child.two_higher()  # This raises an Attribute Error


Exactly. This is even stated quite clearly in PEP 8.

https://www.python.org/dev/peps/pep-0008/


That's just a single underscore for the convention. Double underscore actually mangles the attribute name (it prefixes it with the class name), so that's "really really don't touch this". It's hardly ever used though.


> that's "really really don't touch this".

That's not. The use case for name mangling was "avoid the risk of conflict when designing classes for inheritance": if you're building classes for inheritance, subclasses using the same name for an internal/private attribute are not going to unwittingly collide with the base classe's.


Sure that was the idea, but I don't think I have ever seen any code use it like this.

A single underscore is something that's not part of the classes public API, any child classes may need to change attributes, and by using a double underscore you are saying "I know better than you, you won't ever need to change this", which is never true.

Python isn't like Java where you often have complex and often convoluted class heirachies, where truly private attributes might be more useful.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: