Encapsulation in Python

Encapsulation refers to limiting access to data members within a class. In some programming languages, such as ones that are .NET based, use “getters” and “setters” to make sure data in a class is accessed only by authorized sources. In Python, you would be required to develop your own access modifiers. To create a private variable you prefix the variable name with a double underscore, such as __myVar = 10. Once you do this, variables will not be able to be accessed as previously demonstrated. In previous lessons we just use the = operator to set a variable, such as student1.name = “John Doe”. If we make the variable private then you would need to make a function that takes a value as an argument and sets a private variable. Consider the following WRONG example.


class person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.courses = []

class instructor(person):
    def __init__(self,name,age):
        super().__init__(name, age)
        self.studentsAssigned = 0

    def getDetails(self):
        print("{} has {} students assigned".format(self.name, str(self.studentsAssigned)))

class student(person):
    def __init__(self,name,age):
        super().__init__(name, age)
        self.__grades = []

    def getDetails(self):
        print("{} has the following grades: {}".format(self.name, str(self.grades)))    
    
student1 = student(name="John Doe", age = 21)
student1.__grades.append(90)

Take notice of how we have made courses a private variable by prefixing it with __. If you were to run this code, you would get an error stating, “AttributeError: ‘student’ object has no attribute ‘__grades'”. Now let’s create a function that appends grades to our students using encapsulation.


class person:
    def __init__(self,name,age):
        self.name = name
        self.age = age
        self.courses = []

class instructor(person):
    def __init__(self,name,age):
        super().__init__(name, age)
        self.studentsAssigned = 0

    def getDetails(self):
        print("{} has {} students assigned".format(self.name, str(self.studentsAssigned)))

class student(person):
    def __init__(self,name,age):
        super().__init__(name, age)
        self.__grades = []

    def getDetails(self):
        print("{} has the following grades: {}".format(self.name, str(self.grades)))    
    
    def addGrades(self,grade):
            self.__grades.append(grade)
            print(self.__grades)

student1 = student(name="John Doe", age = 21)
student1.addGrades(90)

Running the code above should output ’90’ to the console. You would want to use encapsulation if you have variables that change a lot or you need to ensure a high level of integrity. The last important thing to note with encapsulation in Python is that you can not make a variable in the parent class private and have a child class access it. Private variables are very narrow in scope and will only communicate with the class it resides in and not with any derived class.

Leave a Comment