This tutorial covers Python private method. We will be giving examples to show you how this method works.
In addition, we will explain how to call private methods, why private methods should be used, and the difference between the other modifiers.
Object-oriented programming languages such as C++, Java, and Python restrict access to class variables and methods by access changes. A class in the majority of computer languages has three access modifiers: Public, Protected, and Private.
Python determines the access control for a specific data member or member function of a class using the ‘_’ symbol. Access specifiers in Python play a crucial role in safeguarding data against unwanted access and preventing its exploitation.
A Class in Python has three types of access modifiers:
- Public Access Modifier
- Protected Access Modifier
- Private Access Modifier
However, our focus in this article is private method. Moving on, let’s know what is Private method in Python!
What is 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 private method you must prefix the member name with double underscore (__).
Note that even the base class cannot access private class methods.
How do you 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 how to run a python script
What is the difference between private and protected in Python?
The difference between private and protected method in Python are 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 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 private method to hide the inner functionality of any class from the outside world. A 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 “__”.
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()
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.
Public method Inside derived class Public method
Name mangling is a magic wand of python which allows 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 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.”
class X: def free(self): print("Public method") def __free(self): print("Private method") obj = X() obj._X__free()
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.
Private variables and methods play a significant role in Python, as we have seen. It provides encapsulation, giving you greater control over how to manage data in real-life problems. It makes data access more versatile by protecting certain data using modifiers such as private, protected, and public mode.