Private method in Python | Example code

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

Private method in Python

Simple example code of private method will restrict on 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 the private methods and attributes of their superclasses. 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 and suggestions on this Python method tutorial.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.