Abstraction in Python

Abstraction is the creation of a base or parent class with a set of generic functions that all child classes will need. Our polymorphism lesson actually uses abstraction by defining a method that can print text based on which class is calling it. You will always need to define the method or function in every class you create. Taking a look at the polymorphism example, you may be asking what the point of defining it in the parent class if you have to define it again in the child class is. Before we answer that, it should be noted that if you remove the function definition from the parent class, the code will still run without error. The reason why you use abstraction in Python comes down to security. The signature of the output is different when a function is called in a child class when it exists in a parent class. From a readability standpoint and general practice, abstraction isn’t really thought about in typical Python projects. We have provided an example below, and it is important to note that the getDetails function is the abstracted method. Since getDetails also displays a different outcome, depending on who calls it, it is also considered polymorphic.


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

        def getDetails(self):
            print("Error: You cannot call details withoout instantiation")

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)))     

people = [student(age=20,name="John Doe"), instructor(age=30, name="Obi Wan")]

for person in people:
    person.getDetails()

1 thought on “Abstraction in Python”

Leave a Comment