如何将一个类的 2 个对象和输出组合添加?



我是这么做的:

class Juice:
def __init__(self, name, capacity):
self.name = name
self.capacity = capacity
def __add__(self,other):
return (self.capacity+other.capacity)

这里我只使用了add方法。

def __add__(self, other):
return (self.name+"&"+other.name)
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)

我应该这样写:Orange&Apple(3.5L)

当您在一个实例上运行print()str()时,会执行您编写的__str__()方法。当您添加ab时,变量result的值为3.5,因此当您打印它时,它将打印3.5。你能做的就是改变__add__()方法,使它返回你想要的格式。

在这个解决方案中,我使用fstrings从__add__()方法打印您想要的文本格式。这样的:

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)

这应该输出

Orange&Apple(3.5L) 

最新更新