Abstract classes in Python

Python Methods and Functions

Why use abstract base classes:
Abstract classes allow you to provide default functionality for subclasses. Compared to interfaces, abstract classes can have an implementation. By defining an abstract base class, you can define a common application programming interface (API) for a set of subclasses. This feature is especially useful in situations where third-party developers provide implementation, for example using plugins in your application, but can also help you when working in a large team or with a large codebase where all the classes are stored in your application. The head is difficult or impossible.

How abstract base classes work:
In python, by default, it cannot provide abstract classes, but python offers a module that provides a base to define abstract base classes (ABC), and this module is called ABC . ABC works by marking base class methods as abstract and then registering concrete classes as implementations of the abstract base. A method becomes abstract if it is decorated with the @abstractmethod keyword. For example —

Code 1:

# Show Python program
# abstract work of the base class

 

from abc import ABC, abstractmethod

 

class Polygon ( ABC):

 

# abstract method

def noofsides ( self ):

  pass

  

class Triangle (Polygon):

 

  # abstract method override

def noofsides ( self ):

print ( " I have 3 sides " )

  

class Pentagon (Polygon):

 

# abstract method override

  def noofsides ( self ):

  print ( "I have 5 sides" )

 

class Hexagon (Polygon):

 

# abstract method override

def noofsides ( self ):

print ( "I have 6 sides" )

  

class Quadrilateral (Polygon):

 

# abstract method override

def noofsides ( self ):

print ( " I have 4 sides " )

 
# Driver code

R = Triangle ()

R.noofsides ()

 

K = Quadrilateral ()

K.noofsides ()

 

R = Pentagon ()

R.noofsides ()

  

K = Hexagon ()

K.noofsides ()

Exit :

 I have 3 sides I have 4 sides I have 5 sides I have 6 sides 

Code 2:

# Show Python program
# abstract work of the base class

 

from abc import ABC, abstractmethod

class Animal (ABC):

  

def move ( self ):

pass

 

class Human (Animal):

 

def move ( self ):

print ( "I can walk and run" )

 

class Snake (Animal):

 

  def move ( self ):

print ( " I can crawl " )

  

class Dog (Animal):

 

def move ( self ):

print ( "I can bark" )

 

class Lion (Animal):

 

def move ( self ):

print ( "I can roar" )

 
# Driver code

R = Human ()

R.move ()

 

K = Snake ()

K.move ()

 

R = Dog ()

R.move ()

 

K = Lion ()

K.move ()

Exit:

 I can walk and run I can crawl I can bark I can roar 

Implementation via subclasses:
Subclasses directly from the base avoid the explicit registration of the class. In this case, Python class control is used to recognize PluginImplementation as an implementation of the abstract PluginBase.

# Show the program Python
# annotation implementation
# class via subclasses

 

import abc

 

class parent: 

def geeks ( self ):

pass

  

class child (parent):

def geeks ( self ):

print ( "child class" )

 
# Driver code

print ( issubclass (child, parent))

print ( isinstance (child (), parent))

Exit:

 True 

A side effect of using direct subclassing is that you can find all implementations of your plugin by asking the base class for a list of known classes derived from it.

Concrete methods in abstract base classes:
Concrete classes contain only concrete ( normal) methods, whereas an abstract class contains both concrete methods and abstract methods. A concrete class provides an implementation for abstract methods, an abstract base class can also provide an implementation by calling methods via super () .
Let's see an example to call a method using super ():

# Python program calling
# super () method

 

import abc

from abc import ABC, abstractmethod

  

class R (ABC):

  def rk ( self ):

print ( "Abstract Base Class" )

 

class K (R):

  def rk ( self ):

  super () .rk ()

print ( "subclass" )

 
# Driver code

r = K ()

r.rk ()

Exit :

 Abstract Base Class sub class 

In the above program, we can call methods in abstract classes using super () .

Abstract properties:
Abstract classes include attributes in addition to methods, you can require attributes in concrete classes by setting them with @abstractproperty.

# Display Python program
# abstract properties

 

import abc

from abc import ABC, abstractmethod

  

class parent (ABC):

@ abc . abstractproperty

def geeks ( self ):

return "parent class"

class child (parent):

  

  @ property

def geeks ( self ):

return "child class"

 

  

try :

r = parent ()

  print (r.geeks)

except Exception as err:

print (err)

 

r = child ()

print (r.geeks)

Output :

 Can't instantiate abstract class parent with abstract methods geeks child class 

In the above example, the base class cannot be created because it only has ab See a straightforward version of the property getter.

Implementing an abstract class:
Abstract classes are incomplete because they have methods that don't have a body. If python allows you to create an object for abstract classes, then use that object in case someone calls the abstract method, but there is no actual implementation to call. Therefore, we use an abstract class as a template and extend and build on it as needed before we can use it. Due to the fact that an abstract class is not a concrete class, it cannot be created. When we create an object for an abstract class, error occurs.

# Show Python program
# abstract class cannot
# be an instance

from abc import ABC, abstractmethod

 

class Animal (ABC):

@ abstractmethod

  def move ( self ) :

pass

class Human (Animal):

  def move ( self ):

print ( " I can walk and run " )

 

class Snake (Animal):

def move ( self ):

print ( "I can crawl " )

  

class Dog (Animal):

def move ( self ):

print ( "I can bark" )

 

class Lion (Animal):

def move ( self ):

print ( " I can roar " )

 

c = Animal ()

Exit :

 Traceback (most recent call last): File "/home/ffe4267d930f204512b7f501bb1bc489.py", line 19, in c = Animal () TypeError: Can' t instantiate abstract class Animal with abstract methods move 




Get Solution for free from DataCamp guru