InterviewSolution
| 1. |
What are abstract base classes in Python? |
|
Answer» A class having one or more abstract methods is an abstract class. A method on the other hand is called abstract if it has a dummy declaration and carries no DEFINITION. Such a class cannot be instantiated and can only be used as a base class to construct a subclass. HOWEVER, the subclass must implement the abstract methods to be a concrete class. Abstract base classes (ABCs) introduce virtual subclasses. They don’t inherit from any class but are still recognized by isinstance() and issubclass() built-in functions. For example, numbers module in standard library contains abstract base classes for all number DATA types. The INT, float or complex class will show numbers. Number class is its super class although it doesn’t appear in the __bases__ attribute. >>> a=10 >>> type(a) <class 'int'> >>> int.__bases__ (<class 'object'>,) #However, issubclass() function returns true for numbers.Number >>> issubclass(int, numbers.Number) True #also isinstance() also returns true for numbers.Number >>> isinstance(a, numbers.Number) TrueThe collections.abc module defines ABCs for Data structures like Iterator, Generator, Set, mapping etc. The abc module has ABCMeta class which is a metaclass for defining custom abstract base class. In the following example Shape class is an abstract base class using ABCMeta. The shape class has area() method decorated by @abstractmethod decorator. import abc class Shape(metaclass=abc.ABCMeta): @abc.abstractmethod def area(self): passWe now create a rectangle class derived from shape class and make it concrete by providing implementation of abstract method area() class Rectangle(Shape): def __init__(self, x,y): self.l=x self.b=y def area(self): return self.l*self.b r=Rectangle(10,20) print ('area: ',r.area())If the abstract base class has more than one abstract method, the child class must implement all of them otherwise TypeError will be RAISED. |
|