+ 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
10 odpowiedzi
+ 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
+ 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.
+ 1
What is your expected output?
Your implementation is correct but seems incomplete...
+ 1
They are asking to return sum of length and some of width.
+ 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...
+ 1
The output gives object type and not addition, unfortunately 😔
+ 1
Thank you for the help. I will try once again
+ 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)
+ 1
Thank you Bob_Li
0
Gouri
without a __str__ definition, what you get when you print s1, s2 or s1+s2 is just the __repr__.