如何制作python数组类的副本?

问题描述 投票:-1回答:1

我正在尝试为迭代自定义自己的类,并尝试将其插入计算中:

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]

为什么mul(it)合并了重载结果?我该如何解决?我想要: print(mul(it))#=> [4,28,90]

python iteration eval pow
1个回答
2
投票

您的__pow__返回一个列表,而不是Iteration实例。 +*操作是列表操作,列表将+*实现为串联和重复。

[[1, 4, 9] + 3 * [1, 8, 27]重复[1, 8, 27] 3次以获得[1, 8, 27, 1, 8, 27, 1, 8, 27],然后将[1, 4, 9][1, 8, 27, 1, 8, 27, 1, 8, 27]连接在一起。

您需要从Iteration返回一个__pow__实例,并且还需要实现__add____mul__,而不仅仅是__pow__。在使用它时,您可能还需要实现__str____repr__,因此在打印时可以看到Iteration对象包装的数据。

© www.soinside.com 2019 - 2024. All rights reserved.