+ 2

Unable to overload +

class Shape: def __init__(self, w, h): self.width = w self.height = h def area(self): return self.width*self.height #your code goes here def __add__(self,other): return Shape(self.width + other.width, self.height + other.height) def gt(self, other): return self.area() > other.area() w1 = int(input()) h1 = int(input()) w2 = int(input()) h2 = int(input()) s1 = Shape(w1, h1) s2 = Shape(w2, h2) print(s1 + s2) print(Shape.gt(s1,s2)) Please correct the code, so that I can get s1 + s2

29th Nov 2022, 12:36 PM
Gouri
10 Answers
+ 5
Adding two shapes creates a new one. Store the new shape to a variable, then print the area of the new shape. gt is supposed to be the "greater than" operator. The magic method is __gt__, not gt. Then you need to print s1 > s2 to compare the areas of the shapes
29th Nov 2022, 1:12 PM
Lisa
Lisa - avatar
+ 2
Can you add question description clearly or task number? one I know is : There it is already given to find area() for the result object as I given. Code is already includes those statements. You may be deleted those lines. Try again by resetting code. Task is to implement addition method only.. And your implementation works fine.
29th Nov 2022, 1:05 PM
Jayakrishna 🇮🇳
+ 1
What is your expected output? Your implementation is correct but seems incomplete...
29th Nov 2022, 12:42 PM
Jayakrishna 🇮🇳
+ 1
They are asking to return sum of length and some of width.
29th Nov 2022, 12:45 PM
Gouri
+ 1
One I found is said to implement overriding method only.. Rest of the code is given already as to "add objects and find area() " So obj = s1 + s2 print( obj.area()) Addition method implemented works...
29th Nov 2022, 12:54 PM
Jayakrishna 🇮🇳
+ 1
The output gives object type and not addition, unfortunately 😔
29th Nov 2022, 1:01 PM
Gouri
+ 1
Thank you for the help. I will try once again
29th Nov 2022, 1:13 PM
Gouri
+ 1
class Shape: def __init__(self, w, h): self.width = w self.height = h def area(self): return self.width*self.height #your code goes here def __str__(self): return f'{self.width},{self.height}' def __add__(self,other): return Shape(self.width + other.width, self.height + other.height) def __gt__(self, other): return self.area() > other.area() w1 = int(input()) h1 = int(input()) w2 = int(input()) h2 = int(input()) s1 = Shape(w1, h1) s2 = Shape(w2, h2) print(s1) print(s2) print(s1+s2) print(s1>s2)
30th Nov 2022, 6:37 AM
Bob_Li
Bob_Li - avatar
+ 1
Thank you Bob_Li
30th Nov 2022, 12:52 PM
Gouri
0
Gouri without a __str__ definition, what you get when you print s1, s2 or s1+s2 is just the __repr__.
30th Nov 2022, 6:34 AM
Bob_Li
Bob_Li - avatar