Python Private Variable And Access Protection Example

In a java-like language, you have the private keyword, which makes certain variables and methods private, preventing external access. However, python does not have this mechanism. Python does this by changing variable and method names. In Python, if you want to make an internal member private, you can put two underscores ( __ ) before the name of the member and that member becomes private ( for example __name ). Private members can only be accessed within the class, not externally.

1. Python Private Class Instance Variables Examples.

In below example, because __name and __age are all private instance variables, so when you use emp.__name to access it, it will throw AttributeError.

class Employee:
    
    title = "Engineer"

    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def print_age(self):
        print('%s: %s' % (self.__name, self.__age))

if __name__ == '__main__':
    
    emp = Employee("tom", 18)

    '''Because __name is private variable, so emp.__name will throw an exception like this AttributeError: 'Employee' object has no attribute '__name'.'''
    emp.__name

But we can add get and set method to access the private variables externally. In this way, not only the data is protected, but also the external access interface is provided. In the methods of get and set, various operations on data such as detecting, processing and wrapping can be added additionally.

class Employee:
    
    title = "Engineer"

    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def print_age(self):
        print('%s: %s' % (self.__name, self.__age))
        
    def set_name(self, name):   
        self.__name = name
        
    def get_name(self):
        return self.__name    
        
    def set_age(self, age): 
        # Verify whether the age value is integer or not.  
        if isinstance(age, int):
            self.__age = age
        else:
            raise ValueError
     
    def get_age(self):
        return self.__age    
        
            

if __name__ == '__main__':
    
    emp = Employee("Tom", 18)
    
    print(emp.get_name())
    
    print(emp.get_age())
    
    # Below code will throw ValueError, because the input value is not integer.
    emp.set_age(88.9)

Below is above code output.

Traceback (most recent call last):
  File "/Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/class/MemberProtection.py", line 44, in <module>
Tom
18
    emp.set_age(88.9)
  File "/Users/songzhao/Documents/WorkSpace/dev2qa.com-example-code/PythonExampleProject/com/dev2qa/example/class/MemberProtection.py", line 29, in set_age
    raise ValueError
ValueError

Besides use emp.get_name() method to access the __name variable value, you can also use emp._Employee.__name to access it also, but this is not recommended. If you want to use emp.__name to access the __name variable value, it will access the emp’s instance variable ( not private variable ) __name, but at this time, the instance variable do not exist, so it will throw an error. Please see below example.

class Employee:
    
    title = "Engineer"

    def __init__(self, name, age):
        self.__name = name
        self.__age = age

    def print_age(self):
        print('%s: %s' % (self.__name, self.__age))
        
    def set_name(self, name):   
        self.__name = name
        
    def get_name(self):
        return self.__name    
        
    def set_age(self, age): 
        # Verify whether the age value is integer or not.  
        if isinstance(age, int):
            self.__age = age
        else:
            raise ValueError
     
    def get_age(self):
        return self.__age    
        
            

if __name__ == '__main__':
    
    emp = Employee("Tom", 18)
    
    # Get emp's __name and __age variable value use get method.
    print(emp.get_name())
    print(emp.get_age())
    
    # Get emp's __name varialbe value use another way.
    print(emp._Employee__name)
    
    ''' Get emp's instance variable __name which do not exist, because private variable __name can not be accessed externally this way. 
    Below code will throw error AttributeError: 'Employee' object has no attribute '__name '''
    print(emp.__name)

Below is above source code output.

    print(emp.__name)
AttributeError: 'Employee' object has no attribute '__name'
Tom
18
Tom

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.