+ 3

Python Juice maker problem

Somebody please help i am getting error in second last line on doing 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 Juice(self.name + '&' + other.name, self.capacity + other.capacity) a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result)

10th Jan 2021, 7:05 AM
Abhishek Dogra
7 Answers
+ 6
def __add__ (self, other): You are adding two objects therefore your dunder/magic method __add__ should be indented inside the class.
10th Jan 2021, 7:44 AM
noteve
noteve - avatar
+ 2
class Juice: def __init__(self, name, capacity): self.name = name self.capacity = capacity # adding two objects def __add__(self, o): return Juice((self.name + "&" +o.name), (self.capacity + o.capacity)) a = Juice("apple", 1.5) b = Juice("orange", 2) c = a + b print(c.name) print(c.capacity) what is wrong with me my code runs on my editor but not sololearn
24th Feb 2021, 8:00 AM
Abebe Adigo
+ 1
Abebe Adigo when I pasted your code into SoloLearn's Coding Playground and ran it, I got the correct result without error: apple&orange 3.5
24th Feb 2021, 11:02 AM
Brian
Brian - avatar
+ 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): 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)
13th May 2021, 2:29 PM
Mayur Pujari
Mayur Pujari - avatar
0
I don't know. My solution is the same, and it passes. Maybe there is a stray unprintable character. Try the 'reset code' option in the hamburger menu and retype it from a clean start. EDIT: Ah yes, 《 Nicko12 》 found it: indentation error on def __add__.
10th Jan 2021, 7:45 AM
Brian
Brian - avatar
0
Tab ?? Return
13th Jan 2021, 2:51 PM
Abhay Parmar
Abhay Parmar - avatar
0
Excpected Output must be: Orange&Apple (3.5L) Your code could be fixed with: return Juice(o.name.capitalize()+ "&" + (self.name.capitalize()), f"({(self.capacity + o.capacity)}L)")
25th Mar 2021, 2:51 PM
Jorge Chavarriaga
Jorge Chavarriaga - avatar