Python 3x Pandas Django

Abstraction


Abstraction in python is the process of hiding the real implementation of an application from the user\machine and emphasizing only on how to use the application.

Example 1

class Class1Students:
    def __init__(self, name, age):
        self.name = name
        self.age  = age

    def speak(self):
        print(f"my name is {self.name}, and I am {self.age} years old.")

student1 = Class1Students("Michael", 40)
student1.speak()                #Output: my name is Michael, and I am 40 years old.
print(student1.age)             #Output: 40

In the above example, abstraction can actually be seen in speak() function right? yes. when we see the line student1.speak(), the abstraction in action because when we run this program we get the string output but we really don't care about how speak() implemented. All we need to know that object student1 is access to speak() method and we can use it and the same with a tuple, string, and etc.

print((1,2,3,4,1).count(1))   #Output: 2

In the above example, we have seen the abstraction in action count() because when we print this line we get the output but we really don't care about how count() is implemented. This is an abstraction.

Abstract Class

Abstract allows you to create a set of methods that must be created within any child classes built from the abstract class.

Any class which contains one or more abstract methods is called an abstract class.

An abstract method is a method that has a declaration but does not have an implementation. While we are designing large functional units we use an abstract class. When we want to provide a common interface for different implementations of a component, we use an abstract class.

How ABC Works

By Default, python does not provide abstract classes but it comes with a module ABC (Abstract Base classes) that provides the base for defining abstract base classes. For example,

from abc import ABC

class Area(ABC):

    def area(self, **kwargs):
          pass

class Circle(Area):
    # overriding abstract method
    def area(self, **kwargs):
        print("Area of Circle : " + str(3.14 * kwargs['radius'] * kwargs['radius']))

class Square(Area):
    # overriding abstract method
    def area(self, **kwargs):
        print("Area of Square : " + str(kwargs['area'] * kwargs['area']))

class Rectangle(Area):
    # overriding abstract method
    def area(self, **kwargs):
        print("Area of Rectangle : " + str(kwargs['length'] * kwargs['breadth']))

circle_obj1 = Circle()
circle_obj1.area(radius=4)

square_obj1 = Square()
square_obj1.area(area=4)

rectangle_obj1 = Rectangle()
rectangle_obj1.area(length=4, breadth=10)

Output:

Area of Circle : 50.24
Area of Square : 16
Area of Rectangle : 40

A method becomes abstract when decorated with the keyword @abstractmethod. For Example,

from abc import ABC, abstractmethod

#abstract base class
class Area(ABC):

    @abstractmethod
    def area(self, **kwargs):
          pass

class Circle(Area):
    # overriding abstract method
    def area(self, **kwargs):
        print("Area of Circle : " + str(3.14 * kwargs['radius'] * kwargs['radius']))

class Square(Area):
    # overriding abstract method
    def area(self, **kwargs):
        print("Area of Square : " + str(kwargs['area'] * kwargs['area']))

class Rectangle(Area):
    # overriding abstract method
    def area(self, **kwargs):
        print("Area of Rectangle : " + str(kwargs['length'] * kwargs['breadth']))

circle_obj1 = Circle()
circle_obj1.area(radius=4)

square_obj1 = Square()
square_obj1.area(area=4)

rectangle_obj1 = Rectangle()
rectangle_obj1.area(length=4, breadth=10)

Output:

Area of Circle : 50.24
Area of Square : 16
Area of Rectangle : 40

Invoke Methods from Abstract Classes

We can define some common stuff in an abstract method and use super() to invoke it in subclasses.

Example 1:

from abc import ABC, abstractmethod

class Animal(ABC):
    @abstractmethod
    def move(self):
        print('Animal moves')

class Cat(Animal):
    def move(self):
        super().move()
        print('Cat moves')

cat_obj = Cat()
cat_obj.move()

Output:

Animal moves
Cat moves

The super() builtin returns a proxy object (temporary object of the superclass) that allows us to access methods of the base class.

Example 2:

from abc import ABC, abstractmethod

class StudentResult(ABC):
    @abstractmethod
    def studentresult(self, Subject1, Subject2):

        if (Subject1 + Subject2)/2 > 50:
              return 'Pass'
        else:
            return 'Fail'

class Student(StudentResult):
    def studentresult(self, Subject1, Subject2):
        result = super().studentresult(Subject1, Subject2)
        print(f"Your total marks is {str(Subject1 + Subject2)} and the final result is {result}" )

obj1 = Student()
obj1.studentresult(Subject1 = 50, Subject2=60)

Output:

Your total marks is 110 and the final result is Pass

An abstract class cannot be instantiated.

from abc import ABC, abstractmethod

#abstract base class
class Area(ABC):

    @abstractmethod
    def area(self, **kwargs):
          pass

area_obj = Area()

Output:

area_obj = Area()

TypeError: Can't instantiate abstract class Area with abstract methods area

If you have any doubts or queries related to this chapter, get them clarified from our Python Team experts on ibmmainframer Community!