0
0
Pythonprogramming~5 mins

Protected attributes in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
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?
ANo prefix
BDouble underscore (__) prefix
CA single underscore (_) prefix
DA dollar sign ($) prefix
Can you access a protected attribute from outside its class?
AYes, but it is discouraged
BNo, it is impossible
COnly if you use special methods
DOnly in subclasses
What does a protected attribute help with in code?
AMaking the attribute public
BIndicating internal use and protecting from accidental changes
CEncrypting the attribute
DPreventing any access
Which of these is a protected attribute name?
A_speed
Bspeed
C__speed
D$speed
What happens if you try to access a protected attribute from outside the class?
AThe program crashes
BPython throws an error
CThe attribute is hidden
DYou can access it, but it’s discouraged
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.