+ 6
Help me in the oop code coach
This is my trial class Juice: def __init__(self, name, capacity): self.name = name self.capacity = capacity def __str__(self): return (self.name + ' ('+str(self.capacity)+'L)') a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result
13 Answers
0
Implement a __add__ method as if it will be called this way
a.__add__(b)
It should return a new Juice object explicitly.
def __add__(self, additive):
return new Juice(x, y)
Where x and y are the new object's name and capacity respectively.
+ 6
I solved it
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,newJuice):
self.name += "&" + str(newJuice.name)
self.capacity += newJuice.capacity
return self.__str__
a = Juice('Orange', 1.5)
b = Juice('Apple', 2.0)
print(a.__add__(b)())
+ 5
Review this chapter, pay extra attention on the second slide.
https://www.sololearn.com/learn/JUMP_LINK__&&__Python__&&__JUMP_LINK/2470/
+ 4
Ipang can you describe it
+ 4
Ore, Eskay๐๐ it has a problem with the line 13
Invalid syntax
+ 4
Ore it just worked
+ 3
<a> __add__ <b>
+ 3
Yep
+ 1
Kintu Michael Evans
I don't know what to describe ...
What you need to add Juice <a> and Juice <b> is to implement __add__ magic method.
+ 1
Kintu Michael Evans that is why __add__ is called a *magic* method
0
There is a cheat to that problem just print the answer directly since it has only one test case, believe me it works ๐๐
0
Kintu Michael Evans WTG! But replace the last line with
print(a + b)