Python, Magic Methods: cannot understand the task

62 Views Asked by At

I'm learning python I should make a task but i cannot understand it :) How the "mississippi" has to be passed to the magic method? I see that only list of integers is passed to the Counter.

Description You have to overload the addition operator in Counter class. Use the add() magic method to overload the addition.

For example, in case of a + b, a object should have add() which accepts b as a second parameter (self goes first).

In this case, Counter object accepts a list from int as a parameter. Object to summarize with will be a str object. The result should be a list of strings which have the following pattern: 1 test - one object from list and str separated by the whitespace.

Default code:

from typing import List


class Counter:
    def __init__(self, values: List[int]):
        self.values = values
    # TODO: add your code here

Example

>>> Counter([1, 2, 3]) + "mississippi"

["1 mississippi", "2 mississippi" , "3 mississippi"]
4

There are 4 best solutions below

0
Edoardo Balducci On BEST ANSWER

When using the __add__ function, you follow a design where the method dynamically accepts the second operand during the operation. This method gives you much more flexibility

So this is a standard implementation:

from typing import List

class Counter:
    def __init__(self, values: List[int]):
        self.values = values

    def __add__(self, other: str) -> List[str]:
        # Create a list of strings by combining each number from self.values with the string 'other'
        return [f"{value} {other}" for value in self.values]

# Example usage:
if __name__ == "__main__":
    counter = Counter([1, 2, 3])
    result = counter + "mississippi"
    print(result)

output: ["1 mississippi", "2 mississippi", "3 mississippi"]

0
Bob On

This is your question:

How the "mississippi" has to be passed to the magic method?

The problem description says:

in case of a + b, a object should have __add__() which accepts b as a second parameter (self goes first)

This tells you that "mississippi" is passed as the b parameter to __add__.

0
Soenderby On

The answer by @Bob is correct. You need to implement the __add__ method.
You can read an explanation of python magic methods here.

What you want is essentially this:

class Counter:
    def __init__(self, values: List[int]):
        self.values = values

    def __add__(self, new_str):
        return [str(value) + " " + new_str for value in self.values]

You can also use a formatted string:

def __add__(self, new_str):
        return [f'{value} {new_str}' for value in self.values]
0
SIGHUP On

An override of __add__ should return self.

class Counter:
    def __init__(self, values: list[int]):
        self._values = values
        self._list = []
    def __add__(self, txt: str):
        self._list = [f"{v} {txt}" for v in self._values]
        return self
    def __str__(self) -> str:
        return repr(self._list)
        
print(Counter([1,2,3]) + "mississippi")

Output:

['1 mississippi', '2 mississippi', '3 mississippi']