我正在尝试为迭代定制自己的类,并尝试将其插入到计算中:
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]
您的
__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
对象正在包装的数据相关问题 更多 >
编程相关推荐