Python Private Method with Examples

What is a private method in Python?

Private methods in Python are only accessible within the class in which they are declared.

Basically, you cannot call a method outside the class.

To indicate a private method you must prefix the member name with double underscore (__).

Note that even the base class cannot access private class methods.

How to call private methods?

Time needed: 2 minutes

Let’s see how we can call private methods in Python. We provide you with steps on how to do it.

  • Step 1. To define a private attribute or function in Python, append an underscore(__).

  • Step 2. Create a class and subclass

    Create a Name class and create a subclass grade that bases its constructor on the Name class.

  • Step 3. Create new methods.

    Create two new methods within the person class, a public and a private method.

  • Step 4. Create a derived class or subclass.

    Now, create the derived class or subclass grade that extends Name:

  • Step 5. Add an argument to the class declaration which is the class name of the parent class.

    This is to extend a class to another class, the argument is the Name class.

  • Step 6. Call the Methods

    The other method is externally called a “public method,” and the other is called a “private method” from their parent class. Let’s see how this works.

  • Step 7. Run the program.

    The call to the work() method is successfully executed, printing out the statements from the work() and the walk() method.
    However, the call to takeCall() triggers an AttributeError because it does not recognize the __call() method from the Name class as a method of the Grade class. Extending a class to another class does not include its own private methods in the extension.

If you having a hard time running your Python program read this article on how to run a Python script

What is the difference between private and protected in Python?

The difference between the private and protected methods in Python is the indicator of prefix name and accessibility.

Basically, the private method indicates its prefix name with two underscore characters  “__”.

You can’t access or modify it from outside the class.

The private method can only be called from within its own class.

However, the protected method is created by starting its name with single underscore”_”.

Protected members can be accessible from outside the class like public members, but they are NOT intended to be so.

Are private methods inherited?

The private method in Python can be inherited, as Python doesn’t have a mechanism that effectively restricts access to instance variables or methods.

The double underscore __ prefixed to a variable makes it private. It gives a strong suggestion not to touch it from outside the class.

Any attempt to do so will result in an AttributeError:

Should I use private methods in Python?

We can use a private method to hide the inner functionality of any class from the outside world.

Private methods are those that should neither be accessible externally nor by base classes.

Also read: Python endswith() Method with Examples

Python Private methods

Private methods are those methods that should neither be accessed outside the class nor by any base class.

In Python, there is no existence of Private methods that cannot be accessed except inside a class.

However, to define a Python private method prefix the member name with double underscore “__”.

Example Program:

class Base:

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

	def __free(self):
		print("Private method")

class Derived(Base):
	def __init__(self):
		
	
		Base.__init__(self)
		
	def call_public(self):
		
		print("\nInside derived class")
		self.free()
		
	def call_private(self):
		
		self.__free()

obj1 = Base()

obj1.free()

obj2 = Derived()
obj2.call_public()

Program explanation:

The above example shows that private methods of the class can neither be accessed outside the class nor by any base class.

However, private methods can be accessed by calling the private methods via public methods.

Output:

Public method

Inside derived class
Public method

Name mangling

Name mangling is a magic wand of Python that allows a private method called outside the class.

Further, name mangling is a method in which any given identifier with one trailing underscore and two leading underscores is explicitly replaced with the __ClassName__  Identifier. In __ClassName__  Identifier name, ClassName is the name of the current class where the identifier is present.

Name mangling is about safety rather than security: it is intended to avoid unintentional access rather than intentional wrongdoing.”

Example program:

class X:
	
	def free(self):
		print("Public method")
	
	def __free(self):
		print("Private method")
		
obj = X()

obj._X__free()

Output:

Private method

Summary

In summary, Python private methods are declared by appending two underscores, (__) to a method’s name.

Declaring private methods allows a method to be reserved exclusively for the class that declares it.

A class that extends a class containing private methods will not inherit them and will generate an error if it attempts to access them.

Leave a Comment