Nodirbek Anorboyev
Nodirbek Anorboyev

Reputation: 25

How can I add One class's 2 objects and output as combined?

Here's what I tried:

class Juice:
    def __init__(self, name, capacity):
        self.name = name
        self.capacity = capacity

    def __add__(self,other):
        return (self.capacity+other.capacity)

Here I used only add method..

    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)

I should have like: Orange&Apple(3.5L)

Upvotes: 1

Views: 169

Answers (1)

Adam
Adam

Reputation: 1565

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) 

Upvotes: 1

Related Questions