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

2024-07-03 01:28:39 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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)组合了重载结果?我怎样才能解决这个问题? 我想: 打印(mul(it))#=>;[4,28,90]


Tags: selfnewlenreturninitdefitarray
1条回答
网友
1楼 · 发布于 2024-07-03 01:28:39

您的__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]

您需要从__pow__返回一个Iteration实例,并且还需要实现__add____mul__,而不仅仅是__pow__。在进行此操作时,您可能还希望实现__str____repr__,以便在打印时可以看到Iteration对象正在包装的数据

相关问题 更多 >