Working on Python Abstract classes |
By default Python does not provide abstract classes Python comes with the ABC module which provides the base for defining Abstract Base classes(ABC) ABC works by decorating methods of the base class as an abstract then registering concrete classes as implementations of the abstract base a method becomes abstract when decorated with the keyword @abstractmethod # Python program showing # abstract base class work from abc import ABC, abstractmethod class Polygon(ABC): @abstractmethod def noofsides(self): pass class Triangle(Polygon): # overriding abstract method def noofsides(self): print("I have 3 sides") class Pentagon(Polygon): # overriding abstract method def noofsides(self): print("I have 5 sides") class Hexagon(Polygon): # overriding abstract method def noofsides(self): print("I have 6 sides") class Quadrilateral(Polygon): # overriding abstract method 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() |
Implementation of Abstract through Subclass |
by subclassing directly from the base, can avoid the need to register the class explicitly the Python class management is used to recognize Plugin implementation as implementing the abstract PluginBase # Python program showing # implementation of abstract # class through subclassing import abc class parent: def geeks(self): pass class child(parent): def geeks(self): print("child class") # Driver code print( issubclass(child, parent)) # True print( isinstance(child(), parent)) # Truea side-effect of using direct subclassing is, it is possible to find all the implementations of the plugin by asking the base class for the list of known classes derived from it |
Concrete Methods in Abstract Base Classes |
abstract classes may contain both concrete methods and abstract methods the concrete class provides an implementation of abstract methods the abstract base class can also provide an implementation can invoke the methods in abstract classes by using super() # Python program invoking a # method using super() from abc import ABC 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() |
Abstract Properties in Python |
abstract classes include attributes/properties can require the attributes in concrete classes by defining them with @abstractproperty # Python program showing # 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)an error is generated by trying to instantiate the abstract class |