DEV Community

Cover image for Intro to Python: Day 6 - Encapsulation vs Abstraction
James Hubert
James Hubert

Posted on

Intro to Python: Day 6 - Encapsulation vs Abstraction

Hi there 👋 I'm a New York City based web developer documenting my journey with React, React Native, and Python for all to see. Please follow my dev.to profile or my twitter for updates and feel free to reach out if you have questions. Thanks for your support!

Today's short post follows up on yesterday's discussion of encapsulating private variables in Python with a double underscore.

In computer science, encapsulation is the practice of making data and processes private within a class or function so that some information is not available to the public. In Python, it is enforced only by convention. We start variables with a double underscore __my_variable to make them private. This doesn't totally enforce the information not being public, but it does serve as a readable warning to other developers that these variables shouldn't be exposed.

Relatedly, abstraction is the concept, strategy, and discussion of how to best hide information within a program, and when to do it. So to simplify the relationship a bit, one way of thinking about this is, abstraction is the theory and encapsulation is the practice.

In many programming languages, Python included, it is a best practice to create getter and setter methods which give limited access to the private variables and data that have been encapsulated. This is another common part of the abstraction process.

Here is an example of a BankAccount class whose constructor creates private instance variables for the account number and balance. Rather than expose those variables directly, we have created getter methods to provide indirect public access which is not easily manipulable on the instance, since it only returns the value of the private variable and does not expose the variable itself.

class BankAccount:
    def __init__(self, account_number, initial_balance):
        self.__account_number = account_number
        self.__balance = initial_balance

    def get_account_number(self):
        return self.__account_number

    def get_balance(self):
        return self.__balance
Enter fullscreen mode Exit fullscreen mode

If you like projects like this and want to stay up to date with more, check out my Twitter @stonestwebdev, I follow back! See you tomorrow for another project.

Top comments (0)