Skip to content
thesarfo

Concept

Encapsulation in Python

Restricting direct access to an object's components using protected and private attribute naming conventions.

views 0

Restricting direct access to certain components of an object, usually by using private variables and methods.

class Person:
def __init__(self, name, age):
self._name = name # Protected attribute
self.__age = age # Private attribute
def display_details(self):
return f"Name: {self._name}, Age: {self.__age}"
# Accessing protected attribute
person = Person("Alice", 30)
print(person._name) # Output: Alice
# Accessing private attribute (not recommended, it's intended to be private)
# This will cause an AttributeError
# print(person.__age)