Interfaces in Python
import math
# Here's a basic interface for geometric shapes.
class Geometry:
def area(self):
pass
def perim(self):
pass
# For our example we'll implement this interface on
# `Rectangle` and `Circle` classes.
class Rectangle(Geometry):
def __init__(self, width, height):
self.width = width
self.height = height
def area(self):
return self.width * self.height
def perim(self):
return 2 * self.width + 2 * self.height
class Circle(Geometry):
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius * self.radius
def perim(self):
return 2 * math.pi * self.radius
# If a variable has an interface type, then we can call
# methods that are in the named interface. Here's a
# generic `measure` function taking advantage of this
# to work on any `Geometry`.
def measure(g):
print(g)
print(g.area())
print(g.perim())
def main():
r = Rectangle(width=3, height=4)
c = Circle(radius=5)
# The `Circle` and `Rectangle` classes both
# implement the `Geometry` interface so we can use
# instances of these classes as arguments to `measure`.
measure(r)
measure(c)
if __name__ == "__main__":
main()This Python code demonstrates the concept of interfaces using abstract base classes. Here’s a breakdown of the translation:
We define a
Geometryclass with abstract methodsarea()andperim(). This serves as our interface.We create
RectangleandCircleclasses that inherit fromGeometryand implement the required methods.The
measure()function takes any object that implements theGeometryinterface.In the
main()function, we create instances ofRectangleandCircleand pass them to themeasure()function.
To run this program, save it as interfaces.py and use:
$ python interfaces.py
<__main__.Rectangle object at 0x...>
12
14
<__main__.Circle object at 0x...>
78.53981633974483
31.41592653589793Python doesn’t have a built-in interface concept like some other languages, but we can achieve similar functionality using abstract base classes or duck typing. This example uses a simple class-based approach to demonstrate the concept.