Python Encapsulation

In this tutorial, you will learn about encapsulation in python

Introduction


Encapsulation is one of the fundamental principles of object-oriented programming (OOP) that allows you to bundle data and methods that operate on the data within a single unit called a class.

It helps in hiding the internal state of an object and restricting access to certain parts of the code.

Python supports encapsulation through the use of private and protected attributes and methods.

 

Understanding Encapsulation


Encapsulation is the bundling of data and methods that operate on the data within a single unit, called a class.

It helps in organizing code and protects the internal state of an object from external interference.

The three main concepts related to encapsulation are access modifiers, private attributes/methods, and protected attributes/methods.

 

Access Modifiers in Python


Access modifiers define the visibility of a class's attributes and methods. In Python, there are three types of access modifiers:

Public Access

Public access is the default access level in Python. Members (attributes and methods) declared as public are accessible from anywhere.

class MyClass:
    def __init__(self):
        self.public_variable = 10

obj = MyClass()
print(obj.public_variable)  # Accessing public attribute

Protected Access

Members declared as protected are accessible within the class and its subclasses. You can denote a protected member by using a single underscore before its name.

class MyClass:
    def __init__(self):
        self._protected_variable = 20

obj = MyClass()
print(obj._protected_variable)  # Accessing protected attribute

Private Access

Members declared as private are only accessible within the class. You can denote a private member by using a double underscore before its name.

class MyClass:
    def __init__(self):
        self.__private_variable = 30

obj = MyClass()
# print(obj.__private_variable)  # This will result in an error

 

Using Encapsulation in Python


Private Attributes and Methods

To achieve encapsulation, you can use private attributes and methods. They are accessible only within the class.

class Car:
    def __init__(self):
        self.__fuel = 100  # Private attribute

    def __update_fuel(self, value):  # Private method
        self.__fuel += value

    def drive(self):
        print("Driving...")
        self.__update_fuel(-10)

car = Car()
car.drive()
# print(car.__fuel)  # This will result in an error
# car.__update_fuel(20)  # This will result in an error

Protected Attributes and Methods

Protected attributes and methods are accessible within the class and its subclasses.

class Animal:
    def __init__(self):
        self._legs = 4  # Protected attribute

    def _make_sound(self):  # Protected method
        pass

class Dog(Animal):
    def bark(self):
        print("Woof!")

dog = Dog()
print(dog._legs)  # Accessing protected attribute
# dog._make_sound()  # Accessing protected method

 

Property Decorators


Property decorators allow you to define methods that can be accessed like attributes.

class Circle:
    def __init__(self, radius):
        self._radius = radius

    @property
    def radius(self):
        return self._radius

    @radius.setter
    def radius(self, value):
        if value > 0:
            self._radius = value
        else:
            print("Invalid radius value")

# Using property
circle = Circle(5)
print(circle.radius)

# Using setter
circle.radius = 7
print(circle.radius)

 

Encapsulation Example


Let's create an example demonstrating encapsulation.

class BankAccount:
    def __init__(self, balance):
        self._balance = balance

    def deposit(self, amount):
        if amount > 0:
            self._balance += amount
            print(f"Deposited ${amount}. New balance: ${self._balance}")
        else:
            print("Invalid deposit amount")

    def withdraw(self, amount):
        if amount > 0 and amount <= self._balance:
            self._balance -= amount
            print(f"Withdrew ${amount}. New balance: ${self._balance}")
        else:
            print("Invalid withdrawal amount")

    def get_balance(self):
        return self._balance

# Using BankAccount class
account = BankAccount(1000)
account.deposit(500)
account.withdraw(200)
print("Current balance:", account.get_balance())

 

Summary


Encapsulation is a crucial concept in object-oriented programming that promotes code organization and data protection. Python provides access modifiers and conventions to implement encapsulation. By using private and protected attributes/methods, you can control the visibility and access of members in your classes, making your code more robust and maintainable.
 

© 2022-2023 All rights reserved.