在其他魔术方法中使用魔术方法


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):
        all_name = self.name + "&" + other.name
        all_capacity = self.capacity + other.capacity
        return(all_name+str(all_capacity))
a = Juice('Orange', 1.5)
b = Juice('Apple', 2.0)
result = a + b
print(result)

我想在__add__中使用__str__而不是str()。那么我该怎么做呢?我能做吗?再次在__add__中,在返回行中,我想使用魔法方法str()而不是原始str()

您遇到的问题是因为str没有在您的对象上被调用,而是在所有容量上被调用,这只是一个正常的Float。

一个非常简单的选择是创建一个新对象。如果你不想这样做,你将需要重组你的__str__实现。下面是你可能会做的一个例子。

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):
        all_name = self.name + "&" + other.name
        all_capacity = self.capacity + other.capacity
        return str(Juice(all_name, all_capacity))
a = Juice('Orange', 1.5)
b = Juice('Apple', 2.0)
result = a + b
print(result)

输出:

Orange&Apple (3.5L)

最新更新