0
0
Pythonprogramming~20 mins

Protected attributes in Python - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Protected Attributes Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of accessing a protected attribute
What is the output of this Python code?
Python
class Car:
    def __init__(self, model):
        self._model = model

car = Car('Tesla')
print(car._model)
AAttributeError
BTesla
CNone
DSyntaxError
Attempts:
2 left
💡 Hint
Protected attributes start with a single underscore but can still be accessed directly.
Predict Output
intermediate
2:00remaining
Accessing protected attribute from subclass
What will this code print?
Python
class Animal:
    def __init__(self):
        self._sound = 'Roar'

class Lion(Animal):
    def make_sound(self):
        return self._sound

lion = Lion()
print(lion.make_sound())
ARoar
BAttributeError
CNone
DTypeError
Attempts:
2 left
💡 Hint
Protected attributes can be accessed inside subclasses.
Predict Output
advanced
2:00remaining
Effect of name mangling on attribute access
What is the output of this code?
Python
class Secret:
    def __init__(self):
        self.__hidden = 'hidden_value'

s = Secret()
print(hasattr(s, '__hidden'))
print(hasattr(s, '_Secret__hidden'))
AFalse\nTrue
BTrue\nFalse
CFalse\nFalse
DTrue\nTrue
Attempts:
2 left
💡 Hint
Double underscore attributes are name-mangled to include the class name.
🧠 Conceptual
advanced
2:00remaining
Understanding protected attribute conventions
Which statement about protected attributes in Python is correct?
AProtected attributes are enforced by Python and cannot be accessed outside the class.
BProtected attributes are the same as private attributes and use double underscores.
CProtected attributes are a naming convention and can be accessed outside the class but should not be.
DProtected attributes are automatically hidden from subclasses.
Attempts:
2 left
💡 Hint
Think about what the single underscore means in Python naming.
Predict Output
expert
2:00remaining
Output when accessing protected attribute with property
What is the output of this code?
Python
class Box:
    def __init__(self):
        self._content = 'secret'

    @property
    def content(self):
        return self._content

b = Box()
print(b.content)
print(b._content)
ANone\nsecret
Bsecret\nAttributeError
CAttributeError\nsecret
Dsecret\nsecret
Attempts:
2 left
💡 Hint
The property returns the protected attribute, which is also accessible directly.