+ 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)
7 Respuestas
+ 6
def __add__ (self, other):
You are adding two objects therefore your dunder/magic method __add__ should be indented inside the class.
+ 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
+ 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
+ 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)
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__.
0
Tab ??
Return
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)")