Search code examples
pythonpython-2.7oopprivate-memberspublic-members

Declaring private variable in Python


I am writing a banking application in Python, and reading some source code from here Banking Application. The balance class is defined below:

class Balance(object):
    """ the balance class includes the balance operations """

    def __init__(self):
        """ instantiate the class """
        self.total = 0

    def add(self, value):
        """ add value to the total
        Args:
            value (int): numeric value
        """
        value = int(value)
        self.total += value

    def subtract(self, value):
        """ subtract value from the total
        Args:
            value (int): numeric value
        """
        value = int(value)
        self.total -= value

My Question

Since balance details should not be accessed outside of a class, we should be defining the attribute self.total as self.__total since we should make it a private rather public variable? Is my line of thinking correct here?


Solution

  • In short: there is no way to have a truly "private" class member in Python. The runtime simply doesn't support memory protection in the way, ex, Java does.

    The double underscore prefix mangles the name so it includes the name of the class it's used in (ex, __total would become _Balance__total), but this is primarily used to allow subclasses to define names which appear the same, but reference different fields.

    The standard convention in Python is to use a single underscore prefix — _total — for class members which should be treated as be "private" or "protected", then trust that the other developers will be adults and respect that (of course, this isn't always a safe assumption…)

    It is very rare to see modern Python code use double-underscore attributes.