+ 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?
3 Réponses
+ 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)
0
You can change the return statement of add method to following one,
return f"{self.name}&{other.name}({self.capacity+other.capacity})"
0
return(self.name+'&'+other.name+ ' ('+str(self.capacity+other.capacity)+'L)')
this shud work,