+ 1

How to fix my code?

class Juice: def __init__(self, name, capacity): self.name = name self.capacity = capacity def __add__(self, other ): self.name = self.name+"&"+other.name self.capacity += other.capacity return self.name,self.capacity a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result) It is the test from course Python core. And it should output: Orange&Apple (3.5L) but it output: (“Orange&Apple”, 3,5)

2nd Dec 2021, 7:23 PM
Timofey Ivanenko
Timofey Ivanenko - avatar
1 Answer
+ 1
class Juice: def __init__(self, name, capacity): self.name = name self.capacity = capacity def __str__(self): return (self.name + ' ('+str(self.capacity)+'L)') def __add__(self, other): cap = self.capacity + other.capacity capstr = " (" + str(cap) + "L" + ")" return self.name + "&" + other.name + capstr a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result) As you can see, you have to make the sum of capacities an string and then add the string to the end of your output rather than returning name and capacity of the name in your add magic method.
3rd Dec 2021, 12:48 PM
Pouria Hosseini
Pouria Hosseini - avatar