Search code examples
pythonaddition

Python, Magic Methods: cannot understand the task


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"]

Solution

  • 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"]