Mam programowania obiektowego modelowania dla geometrycznych kształtach. Muszę dodać metodę w poszczególnych klasach, jeśli chcę, aby dodać dwa kształty geometryczne, ale zostały zdefiniowane w każdej podklasy. W jaki sposób można zaimplementować metodę Add w klasie nadrzędnej, tak, że nie do określił go dla każdego podklasy?
import numpy as np
class Shape(object):
def __repr__(self):
return type(self).__name__
def __str__(self):
return type(self).__name__
class Circle(Shape):
# constructor
def __init__(self, radius):
self.radius = radius
def __add__(self, other):
if type(other) == int:
self.radius = self.radius + other
else:
newRadius = self.radius + other.radius
return Circle(newRadius)
def __radd__(self, other):
return self.__add__(other)
def area(self):
return np.pi * self.radius**2
class Rectangle(Shape):
# constructor
def __init__(self, width,height):
self.width , self.height = width, height
def __add__(self, other):
if type(other) == int:
self.width = self.width + other
self.height = self.height + other
else:
newWidth = self.width + other.width
newHeight = self.Height + other.Height
return Rectangle(newWidth,newHeight)
def __radd__(self, other):
return self.__add__(other)
def area(self):
Function to compute the area of triangle.
return self.width * self.height