DEV Community

Cover image for Intro to Python - Day 5 - Encapsulation in OOP
James Hubert
James Hubert

Posted on

1

Intro to Python - Day 5 - Encapsulation in OOP

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 I continue my boot.dev journey learning Object-Oriented Programming with Python. The topic of the day today is encapsulation.

In any programming language when you create a class or object, there may be variables or methods on the object that you don't want public.

Now encapsulation is not encryption. It's not enough of a safeguard to store truly sensitive information with on the class or object, but in Python it is a convention that helps other developers know which variables they should expose to the public and which should only be accessed with getter / setter methods, or internally within the class.

The convention in Python to designate a private variable is to use a double underscore. If we want to make a private ID method on our Student class, for example:

class Student:
    def __init__(self, name):
        self.name = name
        self.__id = 12345
Enter fullscreen mode Exit fullscreen mode

This lets other developers know that the instance variable __id should not be exposed to the public, and developers should be careful manipulating this variable's value when using the class.

This convention in the language also uses what's called name mangling such that Python (mostly) disallows users from directly accessing variables on a class that start with a double-underscore.

Ideally, private variables are not accessed directly but if need be they should be exposed to the public via a getter method like so:

class Student:
    def __init__(self, name):
        self.name = name
        self.__id = 12345

    def get_student_id(self):
        return self.__id
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.

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

Top comments (0)

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay