+ 2

Python Juice Maker Problem

I have the following code. 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): return (self.name + "&" + other.name, self.capacity + other.capacity) a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result) Which outputs: ('Orange&Apple', 3.5). But the output which is required is: Orange&Apple (3.5L) Does anyone know how to get rid of the ' ' and the , and add brackets around 3.5?

16th Feb 2021, 10:11 AM
Okan
Okan - avatar
3 Respuestas
+ 5
your __add__ method return a tupple instead of a Juice object... you need: def __add__(self, other): return Juice(self.name + "&" + other.name, self.capacity + other.capacity)
16th Feb 2021, 2:25 PM
visph
visph - avatar
0
You can change the return statement of add method to following one, return f"{self.name}&{other.name}({self.capacity+other.capacity})"
16th Feb 2021, 10:17 AM
Abhay
Abhay - avatar
0
return(self.name+'&'+other.name+ ' ('+str(self.capacity+other.capacity)+'L)') this shud work,
13th May 2021, 9:11 PM
Mapurunyane Samuel Tolamo
Mapurunyane Samuel Tolamo - avatar