Python Private Method
In Python, a private method is a method that is not intended to be used outside of the class in which it is defined. These methods are denoted by a double underscore prefix (__) before their name, and they can only be accessed within the class where they are defined. In this article, we are going to discuss the concept of private methods in Python, their advantages and disadvantages, and how to use them with examples.
What is a Private Method in Python?
A private method is a method that is not intended to be used outside the class in which it is defined. These methods are used to implement internal functionality within the class. These are not meant to be used by external code. In Python, private methods are denoted by a double underscore prefix before their name.
How to Define a Private Method in Python?
When the programmer wants to define a private method in Python, then the programmer needs to add a double underscore prefix before the method name. Here is an example:
In the above example, we have defined a class called MyClass. It has a private method called __private_method. This method is called from the class constructor (__init__) using self.__private_method(). Since the method has a double underscore prefix, it is private and cannot be accessed outside the class.
The code provided defines a BankAccount class with methods for depositing and withdrawing funds, displaying the account balance, and printing an account statement. An instance of this class is then created, and some transactions are made to it, followed by printing a statement.
Advantages of Private Methods in Python
Disadvantages of Private Methods in Python
Private methods in Python are a useful feature that can help achieve encapsulation and improve code maintainability. While they have some disadvantages, the benefits of using private methods in Python outweigh the drawbacks.