Summary: In this tutorial, we will learn how to create private member variables and methods in Python.

Private members in programming languages (such as C++ and Java) are the members that are only available to their own class. Neither the subclasses nor the classes in the same package have access to them.

In Python, there is no such strict enforcement of privacy. It does not have access specifiers like other languages to make variables or methods private to the class.

However, we can use the name mangling feature of Python to make a variable or method appear as restricted.

We have to prefix the __ (double underscore) in the name of the variable to represent it as a private variable.

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance    #private variable 
        
    def displayBalance(self):
        print("Balance: ", self.__balance)
        
myaccount = BankAccount('85,33,999')
myaccount.displayBalance()         #outputs 'Balance: 85,33,999'
print(myaccount.__balance)         #AttributeError: object has no attribute '__balance'

Accessing the variable __balance through object throws an error because Python has srambled its name to _BankAccount__balance (class name with leading underscore followed by the name of the variable).

Python does it so to ensure that subclasses don’t accidentally override the private attributes of the parent class.

If we replace the name with _BankAccount__balance in the print statement, then it works fine.

print(myaccount._BankAccount__balance)     #outputs '85,33,999'

The same concept is applicable to methods also. Prefixing the __ in the name of the member methods (__displayBalance), mangles its name (_BankAccount__displayBalance).

class BankAccount:
    def __init__(self, balance):
        self.__balance = balance    #private variable 
    
    #private method    
    def __displayBalance(self):    
        print("Balance: ", self.__balance)
        
myaccount = BankAccount('85,33,999')
myaccount.__displayBalance()         #AttributeError: object has no attribute '__displayBalance'

In the end, we can conclude that Python has no strict mechanism to make variables and methods private. Although, we can prefix __ (double underscore) in the name as to enforce the name mangling, the attributes can still be accessed by the other classes.

References:

Leave a Reply

19 − sixteen =