Featured

    Featured Posts

Python OOPS Tutorial 10:Abstract Classes in Python


Abstraction: - 

§  Hiding the internal implementation and highlighting the set of services that process is called abstraction. 


§  Another way, it shows only important things to the user and hides the internal details for example sending SMS, you just type the text and send the message. You don’t know the internal processing about the message delivery.


§  Abstraction lets you focus on what the object does instead of how it does it.

Ex:-

a.      Bank ATM Screens (Hiding thee internal implementation and highlighting set of services like withdraw, money transfer, mobile registration).

b.     Mobile phones (The mobile persons are hiding the internal circuit implementation and highlighting touch screen).

c.      Syllabus copy (the institutions persons just highlighting the set of contents that persons provided the persons are not highlighting the whole content). 

Abstract Classes in Python

 §  An abstract class can be considered as a blueprint for other classes, allows you to create a set of methods that must be created within any child classes built from your abstract class.



 §  A class which contains one or abstract methods is called an abstract class. An abstract method is a method that has declaration but not has any implementation.



 §  Abstract classes are not able to instantiate, and it needs subclasses to provide implementations for those abstract methods which are defined in abstract classes. While we are designing large functional units, we use an abstract class.



 §  When we want to provide a common implemented functionality for all implementations of a component, we use an abstract class. Abstract classes allow partially to implement classes when it completely implements all methods in a class, then it is called interface.



Why use Abstract Base Classes :

 §  Abstract classes allow you to provide default functionality for the subclasses. Compared to interfaces abstract classes can have an implementation.
     
     By defining an abstract base class, you can define a common Application Program Interface (API) for a set of subclasses. This capability is especially useful in situations where a third-party is going to provide implementations, such as with plugins in an application, but can also help you when working on a large team or with a large code-base where keeping all classes in your head at the same time is difficult or not possible.

  v Abstract classes are classes that contain one or more abstract methods. An abstract method is a method that is declared, but contains no implementation. Abstract classes may not be instantiated, and require subclasses to provide implementations for the abstract methods. Subclasses of an abstract class in Python are not required to implement abstract methods of the parent class.

Abstract Method in Python
  §  Abstract method is a method whose definition is implemented in the sub classes as per the requirements of the objects.

  §  Abstract methods consist of only methods declarations, without any method body.
How to Abstract Method in Python
 §  The method with-out any implementation is known as undefine method.
 §  An abstract method is a method that is declared without an implementation 
 §  The abstract method decorator registers the method as undefined method
    @abstractmethod

@abstractmethod
    def method-name(self):
        pass
 
How Abstract Base classes work :

class C1:
    def m1(self):
        pass
class C2(C1):
    pass

#Create an object of C1
obj1=C1()
#Create an object of C2
obj2=C2()

v  If we start this program, we see that this is not an abstract class, because we can instantiate an instance from
  §  we are not required to implement m1 in the class definition of C2

 v In python by default, it is not able to provide abstract classes, but python comes up with a module which provides the base for defining Abstract Base classes (ABC) and that module name is ABCABC works by marking methods of the base class as abstract and then registering concrete classes as implementations of the abstract base. A method becomes an abstract by decorated it with a keyword @abstractmethod.

For Example –

The following Python code uses the abc module and defines an abstract base class:

from abc import ABC, abstractmethod
class C1(ABC):
    # the abstractmethod decorator registers this method as undefined
    @abstractmethod
    def m1(self):
        pass

#Create an object of C1
obj1=C1()

obj1=C1()
TypeError: Can't instantiate abstract class C1 with abstract methods m1
 §  Now we will define a subclass using the C1 defined abstract class. You will notice that we haven't implemented the m1()  method, even though we are required to implement it, because this method is decorated as an abstract method with the decorator "abstractmethod". We get an exception :

class C2(C1):
    pass

#Create an object of C2
obj2=C2()

obj2=C2()
TypeError: Can't instantiate abstract class C2 with abstract methods m1

§  If the child class haven't implemented the parent class abstract method then child class also becomes abstract class. Then child class can’t be instantiated.
 A class that is derived from an abstract class cannot be instantiated unless all of its abstract methods are overridden.
 
 Ã˜ Ex: -the abstract class contains abstract methods for that abstract methods   
         provide the implementation in child classes. 
from abc import ABC, abstractmethod
class Test1(ABC):
    def m1(self):
        pass
    def m2(self):
        pass
    def m3(self):
        pass
class Test2(Test1):
    def m1(self):
        print('m1-method defined by Test2 Class')
    def m2(self):
        print('m2-method defined by Test2 Class')
    def m3(self):
        print('m3-method defined by Test3 Class')
   
#Creating Child Class Object
t2=Test2()
t2.m1()
t2.m2()
t2.m3()

output:
m1-method defined by Test2 Class
m2-method defined by Test2 Class
m3-method defined by Test3 Class

 Ã˜ Ex: - if the child class is unable to provide the implementation for parent class 
        abstract methods at that situation, we can declare that class is an abstract then take one more child class in that class provide the implementation for remaining methods.

 §  Whenever we inherit ‘n’ number of abstract methods from abstract base class o derived class, if the derived class defines all ‘n’ number of abstract methods then the derived class is concrete class. If the derived class is not defining at least one abstract method out of ‘n’ abstract methods then the derived class is known as abstract derived class and to make that class abstract, we use a keyword called abstract

 §  An abstract base class is one which contains physical representation of abstract methods. An abstract derived class is one which contains logical declaration of abstract methods which are inherited from abstract base class.


from abc import ABC, abstractmethod
class Test1(ABC):
    def m1(self):
        pass
    def m2(self):
        pass
    def m3(self):
        pass
class Test2(Test1):
    def m1(self):
        print('m1-method defined by Test2 Class')
    def m2(self):
        print('m2-method defined by Test2 Class')
   
class Test3(Test2):
    def m3(self):
        print('m3-method defined by Test3 Class')

#Creating Child Class Object
t=Test3()
t.m1()
t.m2()
t.m3()    

output:
m1-method defined by Test2 Class
m2-method defined by Test2 Class
m3-method defined by Test3 Class

 v Demo Program with Polygon Abstract Class



 §  Polygon class that will hold common properties and behaviors for its inheriting classes.



 §  Here we have the abstract class Polygon. we have defined noofsides behaviors which are present in all Polygons.



 §  Polygon can be abstraction for a Triangle,Pentagon,Hexagon,Quadrilateral etc. It acts as a super-categorial noun.



 §  As an abstract concept it can hold all the common properties and behaviors present in different figure.



Program



from abc import ABC, abstractmethod

class Polygon(ABC):

    # the abstractmethod decorator registers this method as undefined

    @abstractmethod

    def noofsides(self):

        pass



class Triangle(Polygon):

    # overriding abstract method

    def noofsides(self):

        print("Triangle have 3 sides")

 

class Pentagon(Polygon):

    # overriding abstract method

    def noofsides(self):

        print("Pentagon have 5 sides")

 

class Hexagon(Polygon):

    # overriding abstract method

    def noofsides(self):

        print("Hexagon have 6 sides")

 

class Quadrilateral(Polygon):

    # overriding abstract method

    def noofsides(self):

        print("Quadrilateral have 4 sides")



# Driver code

T = Triangle()

T.noofsides()

 

Q = Quadrilateral()

Q.noofsides()

 

P = Pentagon()

P.noofsides()

 

H = Hexagon()

H.noofsides() 


output:

Triangle have 3 sides

Quadrilateral have 4 sides

Pentagon have 5 sides

Hexagon have 6 sides



 Demo Program with Shape Abstract Class
 
 §  Here we have the abstract class Shape. We have defined behaviors area () and perimeter () behaviors which are present in all Shape.

 §  Now we have three concreate classes Rectangle,Sqaure,Circle   inheriting from the Shape abstract class.

 §  Shape can be abstraction for a Rectangle,Sqaure,Circle   etc. It acts as a super-categorial noun.

from abc import ABC, abstractmethod
class Shape(ABC):
    # the abstractmethod decorator registers this method as undefined
    @abstractmethod
    def area(self):
        pass
    @abstractmethod
    def perimeter(self):
        pass

class Rectangle(Shape):
    def __init__(self,l,b):
        self.l=l
        self.b=b
    def area(self):
        return (self.l*self.b)
    def perimeter(self):
        return (2*(self.l+self.b))

class Square(Shape):
    def __init__(self,side):
        self.side=side
    def area(self):
        return (self.side*self.side)
    def perimeter(self):
        return (4*(self.side))

class Circle(Shape):
    def __init__(self,radius):
        self.radius=radius
    def area(self):
        return 3.14*(self.radius**2)
    def perimeter(self):
        return (2*3.14*self.radius)

#Creating Rectangle Class Object
r1=Rectangle(10,20)
print('Area of Rectangle=',r1.area())
print('Perimeter of Rectangle=',r1.perimeter())
#Creating Square Class Object
s1=Square(10)
print('Area of Square=',s1.area())
print('Perimeter of Square=',s1.perimeter())
#Creating Circle Class Object
c1=Circle(1.2)
print('Area of Circle=',c1.area())
print('Perimeter of Circle=',c1.perimeter())

output:
Area of Rectangle= 200
Perimeter of Rectangle= 60
Area of Square= 100
Perimeter of Square= 40
Area of Circle= 4.5216
Perimeter of Circle= 7.536

Concrete Methods in Abstract Base Classes:
 §  Concrete classes contain only concrete (normal)methods whereas abstract classes may contain both concrete methods and abstract methods.

Demo Program with Account Abstract Class




 §  Account class that will hold common properties and behaviors for its inheriting classes. 

 §  Here we have the abstract class Account. We have defined properties & behaviors which are present in all Account.

Properties

accno

accholderName

balance

Behaviors

deposit(amount)

withdraw(amount)

balanceEnquiry()


 §  Now we have two concreate classes inheriting from the Account abstract class. We have added some more behaviors specific to the entities.


 §  Account can be abstraction for a CurrentAccount and SavingAccount etc. It acts as a super-categorial noun.



from abc import ABC, abstractmethod

class Account(ABC):

    def __init__(self,accno,accholderName):

        self.accno=accno

        self.accholderName=accholderName

        self.balance=0

    # the abstractmethod decorator registers this method as undefined

    @abstractmethod

    def deposit(self,amount):

        pass

    @abstractmethod

    def withdraw(self,amount):

        pass

    def balanceEnquiry(self):

        return self.balance



class CurrentAccount(Account):

    def __init__(self,accno,accholderName):

        super().__init__(accno,accholderName)

    def deposit(self,amount):

        print(amount,'Rs. Credit in your Current Account')

        self.balance=self.balance+amount

    def withdraw(self,amount):

        print(amount,'Rs. debit from your Current Account')

        self.balance=self.balance-amount

    def processToCheck(self,chequeNo):

        print('Transaction Process through Cheque')



class SavingAccount(Account):

    def __init__(self,accno,accholderName):

        super().__init__(accno,accholderName)

        self.interest=0

    def deposit(self,amount):

        print(amount,'Rs. Credit in your Saving  Account')

        self.balance=self.balance+amount

    def withdraw(self,amount):

        print(amount,'Rs. debit from your Saving  Account')

        self.balance=self.balance-amount

    def monthlyInterest(self):

        self.interest=self.balance*0.05

       

#Driver Code

ca=CurrentAccount(12345,'John')

ca.deposit(10000)

print('Current Balance= ',ca.balanceEnquiry())

ca.withdraw(500)

print('Current Balance= ',ca.balanceEnquiry())

#Creating SavingAccount Object

sa=SavingAccount(784578,'Harry')

sa.deposit(5000)

print('Current Balance= ',sa.balanceEnquiry())

sa.withdraw(500)

print('Current Balance= ',sa.balanceEnquiry())
  

  output:

10000 Rs. Credit in your Current Account

Current Balance= 10000

500 Rs. debit from your Current Account

Current Balance= 9500

5000 Rs. Credit in your Saving Account

Current Balance= 5000

500 Rs. debit from your Saving Account

Current Balance= 4500

 

Demo Program with Plan Abstract Class






 §  Plan class that will hold common properties and behaviors for its inheriting classes.


 §  Here we have the abstract class Plan.We have defined properties rate & behaviors setRate(),calculateBill(units) which are present in all Plan


 §  Now we have Three concreate classes inheriting from the Plan abstract class. 


 §  Plan can be abstraction for a DomesticPlan and CommercialPlan,InstitutionalPlan etc. It acts as a super-categorial noun.

Calculate Electricity Bill : A Real World Example of Factory Method


Step 1: Create a Plan abstract class.

from abc import ABC, abstractmethod

#Create a Plan abstract class.

class Plan:

    def __init__(self):

        self.rate=0.0

    #the abstractmethod decorator registers this method as undefined

    @abstractmethod

    def setRate(self):

        pass

    def calculateBill(self, units):

        print(units*self.rate)


Step 2: Create the concrete classes that inherit  Plan abstract class. 

class DomesticPlan(Plan):

    def setRate(self):

        self.rate=3.6



class CommercialPlan(Plan):

    def setRate(self):

        self.rate=4.2



class InstitutionalPlan (Plan):

    def setRate(self):

        self.rate=5.3


Step 3: Create a GetPlanFactory to generate object of concrete classes based on   

             given information


class GetPlanFactory:

    #use getPlan method to get object of type Plan

    def getPlan(self,planType):

        if planType==None:

            return None

        elif planType=='DOMESTICPLAN':

            return DomesticPlan()

        elif planType=='COMMERCIALPLAN':

            return CommercialPlan()

        elif planType=='INSTITUTIONALPLAN':

            return InstitutionalPlan()

        else:

            return 'Plz Provide Valid Plan Only!.'



Step 4: Generate Bill by using the GetPlanFactory to get the object of concrete classes by passing an information such as type of plan DOMESTICPLAN or COMMERCIALPLAN or INSTITUTIONALPLAN


#Driver Code

planFactory =  GetPlanFactory();

print("Enter the name of plan for which the bill will be generated: ");

print('1.DOMESTICPLAN\n2.COMMERCIALPLAN\n3.INSTITUTIONALPLAN')

planName=input('enter plan Type')

planName=planName.upper() 

units=int(input('Enter the number of units for bill will be calculated:'))

plan= planFactory.getPlan(planName);

print("Bill amount for ",planName," of  ",units," units is: "); 

plan.setRate(); 

plan.calculateBill(units); 


www.CodeNirvana.in

Powered by Blogger.

About

Site Links

Popular Posts

Translate

Total Pageviews