Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
226 views
in Technique[技术] by (71.8m points)

python - 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)

question from:https://stackoverflow.com/questions/65859623/how-can-i-add-one-classs-2-objects-and-output-as-combined

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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) 

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...