Created
December 17, 2017 04:51
-
-
Save Singhak/4c11aeb99cc326b9511e69678d7b33f4 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# need to import ABCMeta, abstractmethod from abc (abstract base classes) module to implement abstract class feature | |
from abc import ABCMeta, abstractmethod | |
# we required (metaclass = ABCMeta) to use feature of abstraction | |
class Shape(metaclass = ABCMeta): | |
#To tell python this is abstractmethod we have to use A decorator indicating abstract methods. | |
@abstractmethod | |
def area(self): | |
pass | |
#now we will inherit Shape class in other concret class | |
class Circle(Shape): | |
def __init__(self, radius): | |
self.radius = radius | |
def area(self): | |
return self.radius**2 * 3.14 | |
class Square(Shape): | |
def __init__(self, side): | |
self.side = side | |
def area(self): | |
return self.side * 2 | |
class Rectangle(Shape): | |
def __init__(self, length, breath): | |
self.length = length | |
self.breath = breath | |
def area(self): | |
return self.breath * self.length | |
circle = Circle(5) | |
square = Square(5) | |
rectangle = Rectangle(5,6) | |
print("area of circle is {}".format(circle.area())) | |
print("area of square is {}".format(square.area())) | |
print("area of rectngle is {}".format(rectangle.area())) | |
# Error | |
class ErrorClass(Shape): | |
def errorPrint(self): | |
print("This implementation give error since we are no implementing area method of abstarct class") | |
err = ErrorClass() | |
err.errorPrint() | |
#output | |
################################################################################################# | |
# area of circle is 78.5 | |
# area of square is 10 | |
# area of rectngle is 30 | |
# --------------------------------------------------------------------------- | |
# TypeError Traceback (most recent call last) | |
# <ipython-input-8-6aaa6b28b92e> in <module>() | |
# 44 print("This implementation give error since we are no implementing area method of abstarct class") | |
# 45 | |
# ---> 46 err = ErrorClass() | |
# 47 err.errorPrint() | |
# | |
# TypeError: Can't instantiate abstract class ErrorClass with abstract methods area | |
####################################################################################################### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment