⬅ Previous Topic
Python Multiple InheritanceNext Topic ⮕
Python Polymorphism⬅ Previous Topic
Python Multiple InheritanceNext Topic ⮕
Python PolymorphismIn the real world, we keep some things private or protected — like your phone password or your bank PIN. In Python, we can also keep some data inside a class private using a concept called encapsulation.
Encapsulation means hiding the details of how something works and only showing what's necessary. This helps keep things safe and organized.
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
person = Person("Alice", 25)
print(person.name) # OK
print(person.age) # OK
person.age = -10 # ❌ Invalid age, but Python allows it!
print(person.age)
Alice
25
-10
We allowed someone to set age
to -10
, which doesn't make sense. We need a way to protect this value.
We can make variables private by using two underscores __
in front of the variable name. This tells Python: "Don’t let anyone access this directly."
class Person:
def __init__(self, name, age):
self.name = name
self.__age = age # Private variable
def get_age(self):
return self.__age
def set_age(self, new_age):
if new_age > 0:
self.__age = new_age
else:
print("Age must be positive.")
person = Person("Bob", 30)
print(person.name) # OK
print(person.get_age()) # OK
person.set_age(-5) # Not allowed
print(person.get_age()) # Still 30
Bob
30
Age must be positive.
30
__age
is a private variable – it cannot be accessed directly from outside.get_age()
is a method to read the age.set_age()
is a method to change the age — but only if it’s valid!print(person.__age)
AttributeError: 'Person' object has no attribute '__age'
This error happens because __age
is private. Python doesn’t allow direct access.
Encapsulation helps keep your data safe. You hide it using private variables and provide special methods to read or change the data — this gives you full control and avoids mistakes.
As you continue learning Python, encapsulation will help you write cleaner, safer, and more professional code. ✅
⬅ Previous Topic
Python Multiple InheritanceNext Topic ⮕
Python PolymorphismYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.