Access Modifiers

Controlling who can see and change your class's data.

Introduction

Python uses naming conventions to indicate how accessible an attribute should be. These conventions are called access modifiers. Unlike some languages that strictly enforce access rules, Python trusts programmers to follow these conventions -- but it does provide one mechanism (name mangling) that makes accidental access harder.

Three Access Levels

Level Syntax Accessible? When to Use
Public self.name Everywhere Data safe to read/write freely
Protected self._name Works, but convention says "internal use" Meant for class and subclasses
Private self.__name Name-mangled; harder to access Sensitive data needing protection

Public Attributes

Public attributes have no special prefix. They can be accessed and modified from anywhere.

class Student:
    def __init__(self, name):
        self.name = name  # public

s = Student("Alice")
print(s.name)      # works fine
s.name = "Bob"     # can change directly
print(s.name)      # Bob

Protected Attributes

A single underscore prefix signals "this is for internal use." Python does not enforce this -- it is a convention that other programmers should respect.

class Employee:
    def __init__(self, name, salary):
        self.name = name
        self._salary = salary  # protected (convention)

e = Employee("Alice", 50000)
print(e._salary)  # works, but shouldn't be accessed directly

Convention, not enforcement: The single underscore is a polite "please do not touch this from outside." It still works if you do, but you are going against the class designer's intention.

Private Attributes

A double underscore prefix triggers name mangling. Python internally renames the attribute, making it harder (but not impossible) to access from outside.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance  # private

acc = BankAccount(1000)
# print(acc.__balance)              # AttributeError!
print(acc._BankAccount__balance)    # 1000 — works but DO NOT do this

Name Mangling Explained

When you write self.__balance, Python internally renames it to _BankAccount__balance. This is called name mangling. It is not true security -- someone determined can still access it -- but it prevents accidental access and makes the intent clear: "this attribute is private."

Python's philosophy: "We are all consenting adults here." Python does not force strict privacy. Instead, it provides conventions and gentle barriers. If you bypass them, you accept the consequences.

OOP Terms

  • Access Modifier: A naming convention (in Python) or keyword (in other languages) that controls the visibility of attributes and methods.
  • Name Mangling: Python's mechanism for making double-underscore attributes harder to access from outside the class.
  • Convention: An agreed-upon practice that is not enforced by the language but followed by the community.

Best Practices

  • Start with private (__) for sensitive data like balances, passwords, and IDs.
  • Use protected (_) for data that subclasses might need but external code should not touch.
  • Keep attributes public only when there is no harm in direct access and modification.

Common Mistakes

  • Using _ClassName__attribute to access private data in production code -- this defeats the purpose.
  • Thinking a single underscore provides any actual protection -- it is purely a naming convention.
  • Making everything private when it does not need to be, making the class hard to use.

Practice Exercises

  1. Create a Person class with a public name, protected _email, and private __password. Try accessing all three from outside the class.
  2. Create a SecretVault class with a private __code. Try accessing it directly, then through name mangling. Observe the difference.
  3. For the Person class above, add a verify_password(guess) method that returns True/False without exposing the actual password.

Summary

  • Python has three access levels: public (no prefix), protected (single underscore), and private (double underscore).
  • Protected is a convention; private uses name mangling for a gentle barrier.
  • Name mangling renames __attr to _ClassName__attr internally.
  • Choose the right level based on how sensitive the data is.