+ 5

Help Operator overloading Python intermediate

This is the project concept: We are improving our drawing application. Our application needs to support adding and comparing two Shape objects. Add the corresponding methods to enable addition + and comparison using the greater than > operator for the Shape class. The addition should return a new object with the sum of the widths and heights of the operands, while the comparison should return the result of comparing the areas of the objects. This is the code that I wrote to solve the project: 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) result = s1 + s2 print(result.area()) print(s1 > s2) This is the error output message: Line 23 Result = s1 +s2 TypeError: unsoported operand type(s) for +: 'Shape' and 'Shape' Can you guys, please help to fix it?

28th May 2022, 2:21 AM
Luzardo Lopez
7 Respuestas
+ 9
Luzardo Lopez Everything is right just change your functions add to __add__ get to __get__
28th May 2022, 2:33 AM
A͢J
A͢J - avatar
+ 3
Thank you AJ
28th May 2022, 2:37 AM
Luzardo Lopez
+ 1
change the function names i.e add to __add__ and gt to __gt__
9th Oct 2022, 8:42 AM
Vishnupriya
+ 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 __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) result = s1 + s2 print(result.area()) print(s1 > s2)
2nd Nov 2023, 6:58 PM
Jens-Andreas Hoheisel
Jens-Andreas Hoheisel - avatar
0
No __get__ doesn't exist as >, __gt__ does
25th Jul 2022, 9:54 AM
Callum
Callum - avatar
0
I literally wrote everything the solution called for and I keep getting an indentation error back but everything is lined up properly. If I move anything, then I get multiple errors.
30th Aug 2023, 8:38 AM
Danial Miller
Danial Miller - avatar
0
I written same as you prescribed from this site but its showing like " you are close fix all bugs in the code".
17th Jan 2024, 3:38 PM
DHODDI RAMANJANEYULU
DHODDI RAMANJANEYULU - avatar