+ 1
How to fix my code?
class Juice: def __init__(self, name, capacity): self.name = name self.capacity = capacity def __add__(self, other ): self.name = self.name+"&"+other.name self.capacity += other.capacity return self.name,self.capacity a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result) It is the test from course Python core. And it should output: Orange&Apple (3.5L) but it output: (“Orange&Apple”, 3,5)
1 Odpowiedź
+ 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):
cap = self.capacity + other.capacity
capstr = " (" + str(cap) + "L" + ")"
return self.name + "&" + other.name + capstr
a = Juice('Orange', 1.5)
b = Juice('Apple', 2.0)
result = a + b
print(result)
As you can see, you have to make the sum of capacities an string and then add the string to the end of your output rather than returning name and capacity of the name in your add magic method.