Object-oriented programming · 4 / 26 Theory

Access control: public, protected and private

Many languages have keywords such as public or private to control who can use an attribute. Python has no such keywords: it relies on naming conventions and on the idea that programmers are responsible adults.

Public attributes

Any name without underscores is public and can be used from anywhere:

class Account:
    def __init__(self, owner):
        self.owner = owner      # public

Protected attributes (_name)

A single leading underscore means "this is internal, do not use it from outside the class". Python does not prevent it, it is only a convention:

class Account:
    def __init__(self, balance):
        self._balance = balance   # protected by convention

a = Account(100)
print(a._balance)   # it works, but it is not recommended

Private attributes (__name)

A double leading underscore activates *name mangling*: Python renames the attribute internally to _ClassName__name, which makes accidental access much more difficult:

class Account:
    def __init__(self, balance):
        self.__balance = balance

    def get_balance(self):
        return self.__balance

a = Account(100)
print(a.get_balance())   # 100
# print(a.__balance)     # AttributeError

It is not real security: a._Account__balance still works. The goal is to avoid name clashes and to signal intention.

Summary

SyntaxMeaning
namepublic
_nameprotected (convention)
__nameprivate (name mangling)

Good practice

Keep internal data protected or private and offer public methods or properties to read and change it in a controlled way. You will see how in the article about getters, setters and properties.