Re:Object Oriented Programming in Python: Encapsulation and ...
by travisjungroth on Sunday September 24, 2017 @12:25PM
(#15325313)
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
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.