मैं ज्यामितीय आकार के लिए ऑब्जेक्ट ओरिएंटेड प्रोग्रामिंग मॉडलिंग की है। मैं जोड़ने के प्रत्येक वर्ग में विधि अगर मैं दो ज्यामितीय आकार को जोड़ने के लिए चाहते हैं, लेकिन मैं हर उपवर्ग में परिभाषित किया गया है। मैं कैसे लागू कर सकते हैं जोड़ने विधि माता पिता कक्षा में है, ताकि मैं हर उपवर्गों के लिए यह परिभाषित करने के लिए नहीं करते हैं?
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