Learn Python OOP encapsulation with real-world examples. Understand public, protected, and private access levels for clean, secure, and maintainable code.
In Python OOP, protected access is a convention that suggests a variable or method should not be accessed directly from outside the class — but it still can be.
A protected member in Python is defined by prefixing its name with a single underscore
_
.
class Car:
def __init__(self):
self._speed = 100 # protected variable
def show_speed(self):
print(f"Speed: {self._speed} km/h")
_speed
is protected, meaning:
class Car:
def __init__(self):
self._speed = 100 # protected
def show_speed(self):
print(f"Speed: {self._speed} km/h")
class SportsCar(Car):
def boost(self):
self._speed += 50
car = SportsCar()
car.boost()
car.show_speed() # ✅ Speed: 150 km/h
Even though _speed
is marked as protected, the subclass can access and modify it.
car = Car()
print(car._speed) # ⚠️ Possible, but not recommended
Python allows it, but by convention, you’re not supposed to do it. Think of it as a “handle with care” warning.
Access Level | Syntax | Meaning |
---|---|---|
Public | name |
Free to access anywhere |
Protected | _name |
Suggests limited access (class or subclass) |
Private | __name |
Strongest hiding (name mangling in Python) |