Encapsulation in Python

Encapsulation is a fundamental concept in object-oriented programming that involves bundling data and methods that operate on that data within a single unit, called a class. The data and methods are then hidden from other classes and can only be accessed through the class methods, providing a level of abstraction and security.

In Python, encapsulation is achieved through the use of access modifiers, such as public, private, and protected. These access modifiers control the visibility of class members from outside the class.

Here is an example of encapsulation in Python:

python
# Define a class with private and public members
class Person:
    def __init__(self, name, age):
        self._name = name    # private member
        self.age = age       # public member

    def get_name(self):
        return self._name

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

# Create an object of the class
person1 = Person("Alice", 30)

# Access the public and private members of the object
print(person1.age)          # Output: 30
print(person1.get_name())   # Output: "Alice"

# Modify the private member of the object
person1.set_name("Bob")
print(person1.get_name())   # Output: "Bob"

In this example, a class called `Person` is defined with two members (`_name` and `age`). The `_name` member is made private by prefixing it with an underscore, indicating that it should not be accessed from outside the class. The `age` member is made public and can be accessed directly from outside the class.

Two methods called `get_name()` and `set_name()` are defined to access and modify the private `_name` member, respectively. An object of the `Person` class is created and its public `age` member and private `_name` member are accessed and modified using the class methods.

Encapsulation is a powerful feature of Python and is used extensively in object-oriented programming to create secure and maintainable code.