0
0
Pythonprogramming~5 mins

Protected attributes in Python

Choose your learning style9 modes available
Introduction

Protected attributes help keep some parts of an object safe from outside changes, but still allow access within the class and its children.

When you want to hide data inside a class but allow child classes to use it.
When you want to prevent accidental changes to important data from outside the class.
When you want to organize your code so some details are kept private but still accessible to related parts.
When you want to signal to other programmers that certain attributes should not be changed directly.
Syntax
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.

Examples
Here, _speed is a protected attribute to store the car's speed.
Python
class Car:
    def __init__(self, speed):
        self._speed = speed  # protected attribute
The child class Dog can access the protected attribute _age from Animal.
Python
class Animal:
    def __init__(self):
        self._age = 5

class Dog(Animal):
    def show_age(self):
        return self._age  # Accessing protected attribute in child class
Sample Program

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.

Python
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
OutputSuccess
Important Notes

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.

Summary

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.