DEV Community

Cover image for Intro to Python: Day 7 - Private Methods in Python
James Hubert
James Hubert

Posted on

Intro to Python: Day 7 - Private Methods in Python

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!

This brief post follows my last three posts which discussed encapsulation vs abstraction and private variables in Python.

In Python, we can prevent other developers from calling certain methods that we want to have private by naming the method with a double-underscore in front just like a private variable.

ex:

class SomeClass:
    def __init__(self):
        self.public_variable = 0
        self.__private_variable = 0

    def my_public_method(self):
        return self.public_variable

    def __my_private_method(self):
        return self.public_variable
Enter fullscreen mode Exit fullscreen mode

In the example above, we create a SomeClass class and define the constructor function to set one public and one private variable on each instance, set to 0.

We then define two methods- one public method called, cleverly, my_public_method, and one private method called __my_private_method. Naming the latter method using the double-underline syntax prevents other programmers from calling the private method on any instance of the class. This allows us to use the method while within the class, but not on each instance.

This can further help with encapsulation when you are working with data you either want private or that you simply don't want exposed for use on each instance.

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)