Private variables and functions





Hello folks...!!!
Today let us look at two types variables namely private and static.

Private variables :

The private variables can be accessed only through the class methods. They cannot be accessed as object_name.variable_name. This is the concept of data hiding. 
Private variables are declared by writing two underscores(__) before the variable name.
Let us look at an example :
class login:
    def __init__(self):
        self.uname=""
        self.__pwd="" #private variable
    
    def add_user(self,a,b):
        self.uname=a
        self.__pwd=b
    def change_pwd(self):
        a=input("Enter old password :")
        if self.__pwd==a:
            self.__pwd=input("Enter new password :")
            print("Password changed")
        else:
            print("Old password wrong!!!")
k=login() 
k.add_user("aaaa","1234")

m=login() 
m.add_user("bbbb","5678")

print(k.uname)
print(k.__pwd)

The output for the above code will be :

private variables

The error is generated because of the line marked in red in the above code. It is because, one cannot access the private variable directly like this.

However they can be accessed through the methods of the class.
 For example : add this line to the above code.
                                        k.change_pwd()
This will yield the output :

Private variable and functions

Private Functions

One can make a function private, so that it cannot be called by the object directly. Any other function within the class call it. For example let us make the method change_pwd() private. Then it cannot be accessed directly as k.change_pwd()
Try the code below in your editor.

class login:
    def __init__(self):
        self.uname=""
        self.__pwd=""
    
    def add_user(self,a,b):
        self.uname=a
        self.__pwd=b
        
    def confirm_change(self):
        inp=input("Change your password for sure ? yes/no")
        if inp=="yes" :
            self.__change_pwd()
        else:
            print("request cancelled")        
            
    def __change_pwd(self):
        a=input("Enter old password :")
        if self.__pwd==a:
            self.__pwd=input("Enter new password :")
            print("Password changed")
        else:
            print("Old password wrong!!!")
k=login() 
k.add_user("aaaa","1234")

m=login() 
m.add_user("bbbb","5678")

print(k.uname)
k.confirm_change()

The output will be :


In the above code, k.confirm_change() calls the private function.


Next Topic👉

Comments