Introduction
Encapsulation helps keep data safe and organized inside a program. It hides details so others use it correctly without breaking it.
Jump into concepts and practice - no test required
Encapsulation helps keep data safe and organized inside a program. It hides details so others use it correctly without breaking it.
class ClassName: def __init__(self, value): self.__private_variable = value # private variable def get_variable(self): return self.__private_variable def set_variable(self, value): self.__private_variable = value
Use double underscore __ before a variable name to make it private.
Use methods (functions inside class) to get or set private data safely.
class BankAccount: def __init__(self, balance): self.__balance = balance # private def get_balance(self): return self.__balance def deposit(self, amount): if amount > 0: self.__balance += amount
class Person: def __init__(self, name): self.__name = name def get_name(self): return self.__name def set_name(self, new_name): self.__name = new_name
This program shows how encapsulation protects the speed value and only allows valid changes.
class Car: def __init__(self, speed): self.__speed = speed # private variable def get_speed(self): return self.__speed def set_speed(self, speed): if speed >= 0: self.__speed = speed car = Car(50) print(car.get_speed()) # prints 50 car.set_speed(80) print(car.get_speed()) # prints 80 car.set_speed(-10) # invalid, ignored print(car.get_speed()) # still prints 80
Encapsulation helps avoid accidental changes to important data.
It makes your code easier to maintain and less error-prone.
Encapsulation hides data inside classes to protect it.
Use private variables and public methods to control access.
This keeps your program safe and organized.
encapsulation in Python classes?__ makes it private.__variable uses double underscore, so it is private.class Box:
def __init__(self):
self.__content = 'secret'
def reveal(self):
return self.__content
b = Box()
print(b.reveal())
print(b.__content)__content is private and cannot be accessed directly outside the class.b.reveal() returns 'secret'. But b.__content causes AttributeError because it's private.class Person:
def __init__(self, name):
self.__name = name
p = Person('Anna')
print(p.__name)__name is private and cannot be accessed directly outside the class.p.__name causes AttributeError because it is private.