Abstract
Abstract
Creating objects of derived classes is possible only when derived classes override
existing functionality of all abstract methods defined in an ABC class.
ABC - Example
In Python, an Abstract Base Class can be created using module abc.
Example 1
ABC - Example...
Example 1...
With existing abstract class definition of Shape, if you try creating a Shape
object it results in TypeError.
s1 = Shape()
Output
TypeError: Can't instantiate abstract class Shape with abstract methods area,
perimeter
ABC - Example...
Example 1...
class Circle(Shape):
def __init__(self, radius):
self.__radius = radius
@staticmethod
def square(x):
return x**2
def area(self):
return 3.14*self.square(self.__radius)
c1 = Circle(3.9)
Creating object c1, with out definingperimeter inside derived class, Circle,
resulted in TypeError.
Output
TypeError: Can't instantiate abstract class Circle with abstract methods perimeter
ABC - Example...
Example 1...
47.7594
Q1
import inspect
if __name__ == '__main__':
if issubclass(Animal, ABC):
print("'Animal' is an abstract class" )
if '@abstractmethod' in inspect.getsource(Animal.say):
print("'say' is an abstract method")
if issubclass(Dog, Animal):
print("'Dog' is dervied from 'Animal' class" )
d1 = Dog()
print("Dog,'d1', says :", d1.say())