0
0
Pythonprogramming~20 mins

Private attributes in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Private Attributes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of accessing a private attribute directly?

Consider this Python class with a private attribute. What happens when we try to print it directly?

Python
class MyClass:
    def __init__(self):
        self.__secret = 'hidden'

obj = MyClass()
print(obj.__secret)
Ahidden
BNone
CAttributeError
DSyntaxError
Attempts:
2 left
💡 Hint

Private attributes are not accessible directly outside the class.

Predict Output
intermediate
2:00remaining
How to access a private attribute using name mangling?

Given a class with a private attribute, what is the output when accessing it using name mangling?

Python
class MyClass:
    def __init__(self):
        self.__secret = 'hidden'

obj = MyClass()
print(obj._MyClass__secret)
Ahidden
BAttributeError
CNone
DSyntaxError
Attempts:
2 left
💡 Hint

Private attributes are stored with a name that includes the class name.

Predict Output
advanced
2:00remaining
What is the output when modifying a private attribute inside a subclass?

Look at this code where a subclass tries to modify a private attribute of its parent. What is printed?

Python
class Parent:
    def __init__(self):
        self.__value = 10

class Child(Parent):
    def __init__(self):
        super().__init__()
        self.__value = 20

obj = Child()
print(obj._Parent__value)
ANone
B20
CAttributeError
D10
Attempts:
2 left
💡 Hint

Private attributes are name-mangled per class, so subclass private attributes are different.

Predict Output
advanced
2:00remaining
What error occurs when trying to access a private attribute with a single underscore?

What happens when you try to access an attribute with a single underscore prefix from outside the class?

Python
class MyClass:
    def __init__(self):
        self._hidden = 'secret'

obj = MyClass()
print(obj._hidden)
Asecret
BAttributeError
CSyntaxError
DNone
Attempts:
2 left
💡 Hint

Single underscore means 'protected' by convention, but no real restriction.

🧠 Conceptual
expert
2:00remaining
Why does Python use name mangling for private attributes?

Choose the best explanation for why Python uses name mangling (double underscore prefix) for private attributes.

ATo make attributes completely inaccessible from outside the class, enforcing strict privacy.
BTo prevent accidental access and name clashes in subclasses by changing the attribute name internally.
CTo optimize memory usage by shortening attribute names at runtime.
DTo allow attributes to be accessed only by functions defined in the same module.
Attempts:
2 left
💡 Hint

Think about how subclasses might accidentally overwrite attributes.