The __str__()
method you wrote is executed when you run print()
or str()
on one instance.
When you added a
and b
the variable result
has the value 3.5
so when you print it, it will print 3.5
.
What you can do is change the __add__()
method so that it returns the format you want.
In this solution I used fstrings to print the format of text you want from the __add__()
method. like this:
class Juice:
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
def __add__(self, other):
return f"{self.name}&{other.name}({self.capacity + other.capacity}L)"
a = Juice("Orange", 1.5)
b = Juice("Apple", 2.0)
print(a + b)
this should output
Orange&Apple(3.5L)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…