0

Why is __str__ method not taking 2 params here.

I'm trying out the juicer program in python core. I want to print the output through the __str__method. This is my code: class Juice: def __init__(self, name, capacity): self.name = name self.capacity = capacity def __add__(self, other): result = self.capacity + other.capacity return result def __str__(self,other): return (self.name + '&' + other.name + ' ('+str(result)+'L)') a = Juice('Orange', 1.5) b = Juice('Apple', 2.0) result = a + b print(result) Error: The special method __str__ takes 0 params(s) , 1 was given. Can someone tell me why the __str__method is showing an error. If I don't mention 2nd argument(other) in str method, there is no error but my output would only be "3.5L" without the names. Also, I want to try printing the result through the str method. How do I do that? Required Output: Orange&Apple 3.5L

24th Jul 2021, 2:05 AM
Kavya
3 Answers
+ 1
The __str__ magic method only has one argument and takes 0 parameters. Think of__str__ to invoke when you call the class inside a print function. The only argument is self which is passed automatically by the class.
24th Jul 2021, 4:06 AM
Saphal Poudyal
Saphal Poudyal - avatar
+ 1
Kavya You should put all your desired output code to __add__ without using __str__ at all.
24th Jul 2021, 9:23 AM
blackfish
blackfish - avatar