Zone Of Makos

Menu icon

Encapsulation in Python

Encapsulation is one of the three main principles of object-oriented programming (OOP), along with inheritance and polymorphism. In Python, encapsulation is the practice of hiding the internal workings of a class and providing access to its properties and methods only through well-defined interfaces. This helps to keep the implementation details of the class hidden from other parts of the program, making it easier to maintain and update. In this lesson, we'll explore how to use encapsulation in Python and how it can help you write more secure and modular code.

Private and Public Variables in Python

In Python, there are no strict access modifiers like in other programming languages. However, you can create private and public variables in Python by convention. Variables that are intended to be private should be prefixed with an underscore, like _variable_name . These variables can still be accessed from outside the class, but it is generally considered bad practice to do so.


class MyClass:
    def __init__(self):
        self._private_variable = "This variable is private"
        self.public_variable = "This variable is public"
        
    def print_variables(self):
        print(self._private_variable)
        print(self.public_variable)

my_object = MyClass()
my_object.print_variables()

print(my_object.public_variable)    # This will print "This variable is public"
print(my_object._private_variable)  # This is technically possible but not recommended

Private and Public Methods in Python

You can also create private and public methods in Python using the same convention as for variables. Private methods should be prefixed with an underscore, like _method_name() . These methods can still be called from outside the class, but again, it is generally considered bad practice to do so.


class MyClass:
    def __init__(self):
        self._private_variable = "This variable is private"
        self.public_variable = "This variable is public"
        
    def _private_method(self):
        print("This is a private method")
        
    def public_method(self):
        print("This is a public method")
        self._private_method()

my_object = MyClass()
my_object.public_method()

my_object._private_method()    # This is technically possible but not recommended

Conclusion

Encapsulation is an important concept in object-oriented programming that allows you to hide the internal workings of a class and provide access to its properties and methods only through well-defined interfaces. In Python, you can create private and public variables and methods using conventions, but it is generally considered bad practice to access private members from outside the class. Encapsulation helps to make your code more modular and secure, and it is an essential part of writing clean and maintainable code.