CodeBlanks Logo Icon CodeBlanks

Private attributes

Learn name mangling with _ and __.

Private attribute convention

In Python, to mark an attribute as private, you prefix it with an underscore: _balance. This is not a rule but a convention; it does not block outside access, yet users are expected not to do it.

Two underscores __balance trigger name mangling: Python rewrites the attribute name as _ClassName__balance. This reduces clashes in subclasses. A single underscore is common for everyday encapsulation.

Outside access

Single-underscore attributes can be accessed from outside; Python does not block it. Still, this breaks the encapsulation agreement. Double-underscore attributes cannot be accessed directly; _ClassName__name is required.

Example: class Account:\n def __init__(self, balance):\n self._balance = balance. a._balance works but is discouraged. Encapsulation aims to make it hard for outside code to mutate internal data directly; we add control with @property.

Practice Add a private attribute to Account

Define a class named Account. Add the method def __init__(self, balance): and in the body write self._balance = balance. Then create an instance with a = Account(100) and print it with print(a._balance).

Starter code

main.py
# Define the Account class

Sample solution

main.py
# Define the Account class
class Account:
    def __init__(self, balance):
        self._balance = balance

a = Account(100)
print(a._balance)

Expected output

100

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which prefix triggers name mangling?

  • _value
  • __value Correct answer
  • value_
  • Value

Explanation: Two underscores turn __value into _ClassName__value.

2 Complete the private attribute

Question
class Account:
    def __init__(self, balance):
        self.____ = balance
Answer
class Account:
    def __init__(self, balance):
        self._balance = balance

Explanation: _balance is a single-underscore private attribute.

3 Match the name conventions

Term Meaning
_value Convention private
__value Name mangling
value Public

All lessons in Intermediate