+ 1

Juice Maker

Hello! I would be grateful for your help in solving the problem. Conditions of the problem: You are given a Juice class, which has name and capacity properties. You need to complete the code to enable and adding of two Juice objects, resulting in a new Juice object with the combined capacity and names of the two juices being added. For example, if you add an Orange juice with 1.0 capacity and an Apple juice with 2.5 capacity, the resulting juice should have: name: Orange&Apple capacity: 3.5 The names have been combined using an & symbol. Use the __add__ method to define a custom behavior for the + operator and return the resulting object. My 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 +'('+str(self.capacity + other.capacity)+'L)') a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result)

22nd Aug 2022, 3:01 PM
Zulfiia Kulanbaeva
Zulfiia Kulanbaeva - avatar
2 Answers
+ 3
Zulfiia Kulanbaeva maybe the __add__ method should return a Juice object: 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 Juice(self.name + '&'+ other.name , self.capacity + other.capacity) a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result) print(result.name) print(result.capacity)
22nd Aug 2022, 3:19 PM
Bob_Li
Bob_Li - avatar
+ 1
Thank you)
23rd Aug 2022, 7:22 AM
Zulfiia Kulanbaeva
Zulfiia Kulanbaeva - avatar