Skip to content

Private method in Python | Example code

  • by

A method that can’t access outside the class or any base class is called the Private method in Python. To define a private method prefix the member name with the double underscore__”.

The private method in Python

A simple example code of a private method will restrict accessing variables and methods directly and can prevent the accidental modification of data.

obj1.__fun() will # raise an AttributeError

obj2.call_private() # will also raise an AttributeError

class Base:

    def fun(self):
        print("Public method")

    # private method
    def __fun(self):
        print("Private method")

# Derived class
class Derived(Base):
    def __init__(self):
        # Base class constructor

    def call_public(self):
        # Calling public method of base class
        print("\nDerived class")

    def call_private(self):
        # Calling private method of base class

obj1 = Base()

obj2 = Derived()


Private method in Python

Why are Python’s ‘private’ methods not actually private?

Answer: Python gives us the ability to create ‘private’ methods and variables within a class by prepending double underscores to the name, like this: __myPrivateMethod().

The name scrambling is used to ensure that subclasses don’t accidentally override their superclasses’ private methods and attributes. It’s not designed to prevent deliberate access from outside.

class Foo(object):
    def __init__(self):
        self.__baz = 42

    def foo(self):

class Bar(Foo):
    def __init__(self):
        super(Bar, self).__init__()
        self.__baz = 21

    def bar(self):

x = Bar()

Output: {‘_Foo__baz’: 42, ‘_Bar__baz’: 21}

Do comment if you have any doubts or suggestions on this Python method tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *