Bird
Raised Fist0
Pythonprogramming~10 mins

Private attributes in Python - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Private attributes
Create object
Set private attribute with __
Access private attribute inside class
Try to access private attribute outside class
Error or no direct access
Use name mangling to access if needed
This flow shows how private attributes are set and accessed inside a class, and how direct access outside is blocked but can be done with name mangling.
Execution Sample
Python
class MyClass:
    def __init__(self):
        self.__secret = 42
    def reveal(self):
        return self.__secret
Defines a class with a private attribute __secret and a method to reveal it.
Execution Table
StepActionVariable/AttributeValueNote
1Create MyClass instanceobjMyClass objectObject created
2Set private attributeobj._MyClass__secret42Inside __init__, private attribute set (name mangled)
3Call reveal methodobj.reveal()42Accesses private attribute inside class
4Try direct accessobj.__secretErrorAttributeError: not accessible directly
5Access with name manglingobj._MyClass__secret42Works due to name mangling
💡 Execution stops after demonstrating private attribute access and restrictions.
Variable Tracker
VariableStartAfter Step 2After Step 3After Step 5
obj._MyClass__secretN/A4242 (inside reveal)42 (via name mangling)
Key Moments - 3 Insights
Why can't we access obj.__secret directly outside the class?
Because Python changes the name internally (name mangling) to _ClassName__secret, so direct access fails as shown in step 4 of the execution_table.
How does the reveal method access the private attribute?
Inside the class, the private attribute __secret is accessible normally, as shown in step 3 where reveal returns 42.
What is name mangling and how does it help?
Name mangling changes __secret to _MyClass__secret internally, allowing access if needed outside the class, as shown in step 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what happens when we try to access obj.__secret directly?
AIt returns None
BIt returns 42
CIt raises an error
DIt creates a new attribute
💡 Hint
See step 4 in the execution_table where direct access causes an error.
At which step does the private attribute get set inside the object?
AStep 1
BStep 2
CStep 3
DStep 5
💡 Hint
Step 2 shows setting obj._MyClass__secret to 42.
If we change the class name to YourClass, how would we access the private attribute outside?
Aobj._YourClass__secret
Bobj.__secret
Cobj._MyClass__secret
Dobj.secret
💡 Hint
Name mangling uses _ClassName__attribute, so with YourClass it changes accordingly.
Concept Snapshot
Private attributes start with __ to hide them from outside access.
Inside the class, you can use them normally.
Outside, direct access causes error.
Python changes the name internally (name mangling).
Access outside is possible with _ClassName__attr syntax.
This helps protect data but is not full security.
Full Transcript
This lesson shows how private attributes work in Python classes. When you create an attribute with two underscores at the start, like __secret, Python changes its name inside the object to include the class name. This is called name mangling. It helps keep the attribute hidden from outside code. Inside the class, you can use the private attribute normally, like in the reveal method. But if you try to access it directly from outside, you get an error. You can still access it outside by using the mangled name, which is _ClassName__secret. This is a way to protect data inside objects but still allow controlled access.

Practice

(1/5)
1. What is the main purpose of using private attributes (starting with __) in a Python class?
easy
A. To speed up the program execution
B. To hide the attribute from outside the class and protect it
C. To make the attribute accessible everywhere
D. To make the attribute a global variable

Solution

  1. Step 1: Understand private attribute naming

    Private attributes start with double underscores to hide them from outside access.
  2. Step 2: Purpose of hiding attributes

    This protects the data inside the object from accidental or unauthorized changes.
  3. Final Answer:

    To hide the attribute from outside the class and protect it -> Option B
  4. Quick Check:

    Private attributes = data protection [OK]
Hint: Private attributes start with __ to hide data inside class [OK]
Common Mistakes:
  • Thinking private means accessible everywhere
  • Confusing private with global variables
  • Believing private speeds up code
2. Which of the following is the correct way to define a private attribute named age in a Python class?
easy
A. self.___age
B. self.age
C. self._age
D. self.__age

Solution

  1. Step 1: Identify private attribute syntax

    Private attributes start with exactly two underscores, like __age.
  2. Step 2: Check options

    self.__age uses self.__age, which is correct. self.age is public, self._age is protected (single underscore), self.___age has three underscores which is invalid.
  3. Final Answer:

    self.__age -> Option D
  4. Quick Check:

    Private attribute = double underscore [OK]
Hint: Private attribute = double underscore before name [OK]
Common Mistakes:
  • Using single underscore instead of double
  • Adding too many underscores
  • Forgetting underscores
3. What will be the output of this code?
class Person:
    def __init__(self, name):
        self.__name = name
    def get_name(self):
        return self.__name

p = Person('Anna')
print(p.get_name())
print(p.__name)
medium
A. Anna\nAnna
B. AttributeError\nAnna
C. Anna\nAttributeError
D. AttributeError\nAttributeError

Solution

  1. Step 1: Understand private attribute access

    The attribute __name is private and cannot be accessed directly outside the class.
  2. Step 2: Check print statements

    Calling p.get_name() returns 'Anna' correctly. But p.__name causes AttributeError because it's private.
  3. Final Answer:

    Anna\nAttributeError -> Option C
  4. Quick Check:

    Private attribute direct access = AttributeError [OK]
Hint: Private attributes cause error if accessed directly outside class [OK]
Common Mistakes:
  • Expecting direct access to private attribute
  • Ignoring AttributeError on private access
  • Confusing method call with attribute access
4. Find the error in this code and fix it:
class Car:
    def __init__(self, model):
        self.__model = model

c = Car('Tesla')
print(c.__model)
medium
A. Add a method inside class to return __model
B. No error, code runs fine
C. Remove underscores from __model
D. Change __model to _model to fix access

Solution

  1. Step 1: Identify the error

    Accessing c.__model outside the class causes AttributeError because __model is private.
  2. Step 2: Fix by adding a getter method

    Adding a method inside the class to return self.__model allows safe access.
  3. Final Answer:

    Add a method inside class to return __model -> Option A
  4. Quick Check:

    Private attribute access needs class method [OK]
Hint: Use class method to access private attributes outside class [OK]
Common Mistakes:
  • Trying to access private attribute directly
  • Removing underscores breaks privacy
  • Ignoring need for getter method
5. You want to store a private attribute __balance in a BankAccount class and allow safe updating only through a method that adds money. Which code snippet correctly implements this?
hard
A. class BankAccount: def __init__(self): self.__balance = 0 def add_money(self, amount): self.__balance += amount def get_balance(self): return self.__balance
B. class BankAccount: def __init__(self): self._balance = 0 def add_money(self, amount): self._balance += amount def get_balance(self): return self._balance
C. class BankAccount: def __init__(self): self.balance = 0 def add_money(self, amount): self.balance += amount def get_balance(self): return self.balance
D. class BankAccount: def __init__(self): self.__balance = 0 def add_money(self, amount): self.balance += amount def get_balance(self): return self.__balance

Solution

  1. Step 1: Check private attribute usage

    class BankAccount: def __init__(self): self.__balance = 0 def add_money(self, amount): self.__balance += amount def get_balance(self): return self.__balance uses self.__balance consistently and privately.
  2. Step 2: Verify method updates and access

    The add_money method safely updates __balance, and get_balance returns it correctly.
  3. Final Answer:

    The code using self.__balance consistently in all methods -> Option A
  4. Quick Check:

    Private attribute updated only inside class methods [OK]
Hint: Update private attributes only via class methods [OK]
Common Mistakes:
  • Updating private attribute outside class
  • Mixing private and public attribute names
  • Not providing method to access private data