Protected attributes help keep some parts of an object safe from outside changes, but still allow access within the class and its children.
Protected attributes in Python
class ClassName: def __init__(self): self._protected_attribute = value
Protected attributes start with a single underscore _.
This is a convention in Python, not a strict rule. It tells others to be careful with these attributes.
_speed is a protected attribute to store the car's speed.class Car: def __init__(self, speed): self._speed = speed # protected attribute
Dog can access the protected attribute _age from Animal.class Animal: def __init__(self): self._age = 5 class Dog(Animal): def show_age(self): return self._age # Accessing protected attribute in child class
This program shows a protected attribute _age in a class Person. The child class Employee can change it safely. Outside code can access it but should avoid doing so directly.
class Person: def __init__(self, name, age): self.name = name self._age = age # protected attribute def show_age(self): return f"Age is {self._age}" class Employee(Person): def birthday(self): self._age += 1 # allowed to change protected attribute p = Person("Alice", 30) print(p.name) # Access public attribute print(p._age) # Access protected attribute (possible but not recommended) print(p.show_age()) # Access protected attribute via method e = Employee("Bob", 25) e.birthday() print(e.show_age()) # Shows updated age
Protected attributes are a convention, not enforced by Python.
Use protected attributes to signal 'handle with care' to other programmers.
For stricter hiding, Python uses double underscores for private attributes.
Protected attributes start with a single underscore _.
They are meant to be used inside the class and its child classes.
Outside code can access them but should avoid changing them directly.
Practice
_value) in a Python class attribute indicate?Solution
Step 1: Understand underscore usage in Python
A single underscore prefix means the attribute is intended for internal use, signaling protection but not strict privacy.Step 2: Differentiate from private and public
Private attributes use double underscores, public have no underscore, and constants are uppercase without underscores.Final Answer:
It is a protected attribute meant for internal use within the class and subclasses. -> Option BQuick Check:
Single underscore = protected attribute [OK]
- Confusing single underscore with private (double underscore)
- Thinking single underscore makes attribute inaccessible
- Assuming single underscore means public attribute
_count inside a Python class?Solution
Step 1: Identify protected attribute syntax
Protected attributes start with a single underscore, soself._countis correct.Step 2: Check other options
self.countis public,self.__countis private, andcount = 0is a local variable, not an attribute.Final Answer:
self._count = 0 -> Option AQuick Check:
Protected attribute = single underscore prefix [OK]
- Using no underscore for protected attribute
- Using double underscore for protected instead of private
- Defining attribute without self inside methods
class MyClass:
def __init__(self):
self._value = 10
obj = MyClass()
print(obj._value)Solution
Step 1: Understand protected attribute access
Protected attributes can be accessed outside the class, though it is discouraged.Step 2: Check code behavior
The attribute_valueis set to 10 and printed directly, so output is 10.Final Answer:
10 -> Option CQuick Check:
Protected attribute accessible outside class = 10 [OK]
- Expecting AttributeError when accessing protected attribute
- Confusing protected with private attributes
- Thinking protected attributes are hidden
class Parent:
def __init__(self):
self._data = 5
class Child(Parent):
def print_data(self):
print(self.data)
c = Child()
c.print_data()Solution
Step 1: Check attribute names in Parent and Child
Parent definesself._data, but Child tries to printself.data, which does not exist.Step 2: Understand error type
Accessing a non-existent attribute causes AttributeError at runtime.Final Answer:
AttributeError becauseself.datadoes not exist -> Option DQuick Check:
Wrong attribute name = AttributeError [OK]
- Ignoring underscore in attribute name
- Assuming protected attribute is private and inaccessible
- Confusing syntax errors with attribute errors
BankAccount with a protected attribute _balance that can be safely accessed and updated only by subclasses. Which code snippet correctly implements this?Solution
Step 1: Identify protected attribute usage
class BankAccount: def __init__(self, balance): self._balance = balance class SavingsAccount(BankAccount): def deposit(self, amount): self._balance += amount acc = SavingsAccount(100) acc.deposit(50) print(acc._balance) usesself._balancewhich is protected and accessible in subclass.Step 2: Check attribute access and update
Subclass methoddepositupdatesself._balancecorrectly. Printingacc._balanceshows updated value.Step 3: Analyze other options
class BankAccount: def __init__(self, balance): self.__balance = balance class SavingsAccount(BankAccount): def deposit(self, amount): self.__balance += amount acc = SavingsAccount(100) acc.deposit(50) print(acc.__balance) uses double underscore (private), so subclass cannot access__balancedirectly. class BankAccount: def __init__(self, balance): self.balance = balance class SavingsAccount(BankAccount): def deposit(self, amount): self.balance += amount acc = SavingsAccount(100) acc.deposit(50) print(acc.balance) uses public attribute. class BankAccount: def __init__(self, balance): _balance = balance class SavingsAccount(BankAccount): def deposit(self, amount): _balance += amount acc = SavingsAccount(100) acc.deposit(50) print(_balance) uses local variable_balancenot attached to self, causing errors.Final Answer:
Usesself._balance(single underscore) in parent and subclass. -> Option AQuick Check:
Protected attribute with single underscore and subclass access = class BankAccount: def __init__(self, balance): self._balance = balance class SavingsAccount(BankAccount): def deposit(self, amount): self._balance += amount acc = SavingsAccount(100) acc.deposit(50) print(acc._balance) [OK]
- Using double underscore for protected attribute
- Not using self. to define attributes
- Using local variables instead of instance attributes
Ready to prove it?
Pass the test and this pattern moves unknown
