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
        Base.__init__(self)

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

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


obj1 = Base()
obj1.fun()
obj1.__fun()

obj2 = Derived()
obj2.call_public()
obj2.call_private()

Output:

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):
        print
        self.__baz


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

    def bar(self):
        print
        self.__baz


x = Bar()
x.foo()
x.bar()
print(x.__dict__)

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 *