Python Encapsulation

Encapsulation is one of the key principles of object-oriented programming (OOP) and refers to the practice of hiding internal data and methods of an object from the outside world, while exposing a public interface that can be used to interact with the object.

In Python, encapsulation is typically achieved by using access modifiers to control the visibility of class members. There are three access modifiers in Python: public, protected, and private.

1. Public Access Modifier:

Public members are accessible from outside the class without any restrictions. In Python, all members of a class are public by default, which means that they can be accessed from anywhere in the program.

Example:

class MyClass:
    def __init__(self):
        self.public_member = "I am a public member"

my_object = MyClass()
print(my_object.public_member)   # Output: "I am a public member"

2. Protected Access Modifier:

Protected members are accessible only within the class and its subclasses. To define a protected member in Python, you can prefix the member name with a single underscore (_). Although the member can be accessed from outside the class, it is generally considered a bad practice to do so.

Example:

class MyClass:
    def __init__(self):
        self._protected_member = "I am a protected member"

class MySubclass(MyClass):
    def __init__(self):
        super().__init__()
        print(self._protected_member)   # Output: "I am a protected member"

my_object = MyClass()
print(my_object._protected_member)   # Output: "I am a protected member"

Private Access Modifier:

Private members are accessible only within the class. To define a private member in Python, you can prefix the member name with two underscores (__). This is also known as name mangling, which means that the member name is modified to prevent it from being accessed from outside the class.

Example:

class MyClass:
    def __init__(self):
        self.__private_member = "I am a private member"

    def get_private_member(self):
        return self.__private_member

my_object = MyClass()
print(my_object.get_private_member())   # Output: "I am a private member"
print(my_object.__private_member)   # Error: 'MyClass' object has no attribute '__private_member'
Wordpress Social Share Plugin powered by Ultimatelysocial
Wordpress Social Share Plugin powered by Ultimatelysocial