Recall & Review
beginner
What is a private attribute in Python?
A private attribute is a variable inside a class that is meant to be hidden from outside access. It usually starts with two underscores (e.g., <code>__name</code>) to indicate it should not be accessed directly from outside the class.Click to reveal answer
beginner
How do you define a private attribute in a Python class?
You define a private attribute by starting its name with two underscores, like
self.__age = 25. This tells Python to mangle the name to make it harder to access from outside.Click to reveal answer
beginner
Why use private attributes in a class?
Private attributes help protect data inside an object. They prevent accidental changes or misuse from outside the class, helping keep the object's state safe and controlled.
Click to reveal answer
intermediate
What happens if you try to access a private attribute directly from outside the class?
Python will raise an
AttributeError because the attribute name is changed internally (name mangling). You cannot access it by its original name directly.Click to reveal answer
intermediate
How can you access a private attribute from outside the class if needed?You can access it using the mangled name, which is <code>_ClassName__attribute</code>. For example, if the class is <code>Person</code> and attribute is <code>__age</code>, access it as <code>instance._Person__age</code>. But this is not recommended.Click to reveal answer
How do you declare a private attribute in a Python class?
✗ Incorrect
Private attributes start with two underscores to trigger name mangling and hide them from outside access.
What error do you get if you try to access a private attribute directly?
✗ Incorrect
Trying to access a private attribute directly raises AttributeError because the name is mangled internally.
Which of these is the correct way to access a private attribute from outside the class (not recommended)?
✗ Incorrect
Private attributes are accessed outside the class using the mangled name: _ClassName__attribute.
Why should you use private attributes?
✗ Incorrect
Private attributes protect data inside the object from accidental or unauthorized changes.
What is name mangling in Python?
✗ Incorrect
Name mangling changes private attribute names by adding the class name prefix to make them harder to access directly.
Explain what private attributes are and why they are useful in Python classes.
Think about how you keep some things private in real life and how that idea applies to programming.
You got /4 concepts.
Describe how Python handles private attributes internally and how you can access them if needed.
Imagine a secret code that changes the name so only the class knows it.
You got /4 concepts.