【问题标题】:how to make a replica of python array class?如何制作python数组类的副本?
【发布时间】:2020-04-01 11:06:50
【问题描述】:

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

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]

【问题讨论】:

  • 当 x 为 it 时,x**2 的值是什么?

标签: python iteration eval pow


【解决方案1】:

您的 __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 对象包装的数据。

【讨论】:

    猜你喜欢
    • 2011-09-25
    • 2015-03-04
    • 2012-01-02
    • 1970-01-01
    • 2014-01-17
    • 1970-01-01
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    相关资源
    最近更新 更多