Recall & Review
beginner
What is a protected attribute in Python?
A protected attribute is a variable in a class that is intended to be accessed only within the class and its subclasses. It is marked by a single underscore prefix (e.g., <code>_attribute</code>).Click to reveal answer
beginner
How do you define a protected attribute in a Python class?
You define it by prefixing the attribute name with a single underscore, like
self._name = value. This signals it is for internal use only.Click to reveal answer
beginner
Can protected attributes be accessed from outside the class in Python?Yes, they can be accessed from outside, but it is discouraged. The single underscore is a convention to indicate 'please don’t touch this' rather than a strict rule.
Click to reveal answer
intermediate
Why use protected attributes instead of public ones?
Protected attributes help organize code by showing which parts are internal and should not be changed directly. This helps avoid bugs and makes maintenance easier.
Click to reveal answer
beginner
Example: What does this code do?
<pre>class Car:
def __init__(self, model):
self._model = model
car = Car('Toyota')
print(car._model)</pre>This code creates a Car object with a protected attribute
_model. It then prints the model name 'Toyota'. Accessing _model works but is discouraged outside the class.Click to reveal answer
What prefix is used to mark a protected attribute in Python?
✗ Incorrect
Protected attributes use a single underscore (_) prefix to indicate they are for internal use.
Can you access a protected attribute from outside its class?
✗ Incorrect
Protected attributes can be accessed from outside, but the single underscore signals you should not do it.
What does a protected attribute help with in code?
✗ Incorrect
Protected attributes show which parts of code are internal and should not be changed directly.
Which of these is a protected attribute name?
✗ Incorrect
A single underscore prefix like '_speed' marks a protected attribute.
What happens if you try to access a protected attribute from outside the class?
✗ Incorrect
Python allows access but the underscore warns you not to do it.
Explain what a protected attribute is and why you might use it in a Python class.
Think about how you tell others not to change something in your code.
You got /4 concepts.
Describe the difference between protected and private attributes in Python.
Focus on the number of underscores and how Python treats them.
You got /4 concepts.