Search code examples
pythoniterationevalpow

how to make a replica of python array class?


I am trying to customize my own class for iteration, and tries to plug it into the calculations:

class Iteration:
    def __init__(self, array):
        self.array = array

    def __pow__(self, power, modulo=None):
        new_array = list()
        for i in self.array:
            new_array.append(i ** power)
        return new_array

    def __len__(self):
        return len(self.array)

    def __getitem__(self, indices):
        return self.array[indices]


def mul(x):
    return x ** 2 + 3 * x ** 3


it = Iteration([1, 2, 3])

print(mul(2))   #=> 28
print(mul(it))  #=> [1, 4, 9, 1, 8, 27, 1, 8, 27, 1, 8, 27]

why mul(it) has combined overloaded result? How can I solve this? I want: print(mul(it)) #=> [4, 28, 90]


Solution

  • Your __pow__ returns a list, not an Iteration instance. The + and * operations are list operations, and lists implement + and * as concatenation and repetition.

    [1, 4, 9] + 3 * [1, 8, 27] repeats [1, 8, 27] 3 times to get [1, 8, 27, 1, 8, 27, 1, 8, 27], then concatenates [1, 4, 9] and [1, 8, 27, 1, 8, 27, 1, 8, 27].

    You need to return an Iteration instance from __pow__, and you need to implement __add__ and __mul__ too, not just __pow__. While you're at it, you might also want to implement __str__ or __repr__, so you can see the data your Iteration object is wrapping when you print it.