Python Tutorial

Python Variable

Python Operators

Python Sequence

Python String

Python Flow Control

Python Functions

Python Class and Object

Python Class Members (properties and methods)

Python Exception Handling

Python Modules

Python File Operations (I/O)

Python Encapsulation Principle

In Python, encapsulation is a principle of object-oriented programming that involves hiding the implementation details of a class from the outside world and making the class's attributes and methods accessible only through a well-defined interface.

Encapsulation is used to protect the internal state of a class and prevent it from being modified directly. This is important because it allows you to ensure the correctness of the class's behavior and maintain the integrity of its internal state.

To achieve encapsulation in Python, you can use private attributes and methods, which are defined using a double underscore (__) prefix. Private attributes and methods are inaccessible from outside the class, preventing them from being modified directly. To access or modify private attributes, you can define getter and setter methods that provide controlled access to the attribute values.

Here's an example of encapsulating a Python class using private attributes and getter and setter methods:

class Person:
    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def get_name(self):
        return self.__name

    def set_name(self, name):
        self.__name = name

    def get_age(self):
        return self.__age

    def set_age(self, age):
        self.__age = age

In this example, we define a class called Person with two private attributes, __name and __age. The class also defines getter and setter methods for each attribute, which allows controlled access to the attribute values.

To access the name attribute of a Person instance, you can call the get_name() method:

person = Person("Alice", 30)
name = person.get_name()
print(name)  # Output: "Alice"

To modify the name attribute of a Person instance, you can call the set_name() method:

person = Person("Alice", 30)
person.set_name("Bob")
name = person.get_name()
print(name)  # Output: "Bob"

In this way, the implementation details of the Person class are hidden from the outside world, and the attribute values can only be modified in a controlled way through the defined getter and setter methods. This helps ensure the internal state of the class is protected and that it can only be modified in a controlled way.

In summary, encapsulation is an important principle of object-oriented programming that involves hiding the implementation details of a class from the outside world and making the class's attributes and methods accessible only through a well-defined interface. This helps ensure the correctness of the class's behavior and maintain the integrity of its internal state.