+ 1
Operator overloading
#idk what to do (for operator overloading in python developer) 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 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)
8 Answers
+ 2
Letâs take a look on the task description and the test case 1 as example.
1. The addition should "return a new object" with the "sum of the widths and heights of the operands".
2. The comparison should return the result of "comparing the *areas of the *objects."
Test Case 1 Input:
w1 = 2
h1 = 3
w2 = 4
h2 = 2
Test Case 1 Expected Output:
print(result.area()) returns 30
print(s1 > s2) returns False
Task 1 description is a little bit confusing. By looking at the expected result (30), it turns out to be:
(w1 + w2) * (h1 + h2) >> (2+4) * (3+2) >> 6 * 5 >> 30
It is your task to figure out how to "return a new object" with overloading.
Task 2 is much easier. Notice I put * before areas and objects. Both are plural.
As s1's area (2 * 3 = 6) is smaller than s2's (4 * 2 = 8), it returns False.
It is also your task to figure out how to do it with overloading.
+ 3
When I feel overwhelmed by a task, I find it helpful to break it up into smaller tasks.
Here is the problem:
"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."
So let's start with adding the first method, what magic method is used to define addition for the class?
+ 1
I saw it was "__add__" and "__lt__"
+ 1
The logic applies to all test cases. Replace the variable with given number and do the calculation.
Also please take a closer look to the given code.
It gave you print(s1 > s2), why would you overloading the magic method "__lt__"?
+ 1
Uhhh, idk
+ 1
It's going to be similar to the add method, but instead of adding the sides together, you're comparing the areas of 2 Shapes. Specifically with the "<" comparator
0
Thanks for the better explination, what about Test Case 2?
0
Hmm, ok