Encapsulation is one of the fundamental principles of object-oriented programming (OOP), aiming to bundle the data (attributes) and methods (functions) that operate on the data into a single unit or class.
In Python, encapsulation is achieved through conventions rather than strict enforcement through language features.
Encapsulation prevents data modification accidentally by limiting access (with the help of Encapsulation through naming conventions) to attributes and methods. An object's method can change an attribute's value to prevent accidental changes.
These are accessible from outside the class. By default, all attributes and methods are public in Python.
# declare custom class class YourClass: # intialize constructor method def __init__(self): # intialize public attribute self.public_attribute = "I am a public attribute" # intialize public method def public_method(self): return "This is a public method"
These are denoted by a single underscore "_", indicating that they are intended for internal use, but they can still be accessed from outside the class.
class YourClass: def __init__(self): self._protected_attribute = "I am a protected attribute" def _protected_method(self): return "This is a protected method"
These are denoted by double underscores `__`.
They are inaccessible from outside the class except through special methods like name mangling.
class YourClass: def __init__(self): self.__private_attribute = "I am a private attribute" def __private_method(self): return "This is a private method"
class Car: def __init__(self, brand, model): self._brand = brand # protected attribute self.__model = model # private attribute def drive(self): return f"Driving {self._brand} {self.__model}" def __maintenance(self): return f"{self._brand} {self.__model} is under maintenance" # Creating an object of Car your_car = Car("Toyota", "Camry") # Accessing public method print(your_car.drive()) # Output: Driving Toyota Camry # Accessing protected attribute (not recommended, but possible) print(your_car._brand) # Output: Toyota # Attempting to access private attribute (will result in AttributeError) # print(your_car.__model) # Attempting to access private method (will result in AttributeError) # your_car.__maintenance()
In Python, Encapsulation is achieved mainly through conventions, and there's no strict enforcement to prevent access to protected or private members.
However, developers are encouraged to follow these conventions to maintain code integrity and facilitate collaboration.