我最初是将它作为一个围绕列表的包装类来实现的,但是我对需要提供的操作符()方法的数量感到恼火,所以我尝试简单地将list子类化。这是我的测试代码:
class CleverList(list):
def __add__(self, other):
copy = self[:]
for i in range(len(self)):
copy[i] += other[i]
return copy
def __sub__(self, other):
copy = self[:]
for i in range(len(self)):
copy[i] -= other[i]
return copy
def __iadd__(self, other):
for i in range(len(self)):
self[i] += other[i]
return self
def __isub__(self, other):
for i in range(len(self)):
self[i] -= other[i]
return self
a = CleverList([0, 1])
b = CleverList([3, 4])
print('CleverList does vector arith: a, b, a+b, a-b = ', a, b, a+b, a-b)
c = a[:]
print('clone test: e = a[:]: a, e = ', a, c)
c += a
print('OOPS: augmented addition: c += a: a, c = ', a, c)
c -= b
print('OOPS: augmented subtraction: c -= b: b, c, a = ', b, c, a)
正常的加减法按预期的方式工作,但增广加减法存在问题。输出如下:
^{pr2}$在这个例子中,有没有一种简单明了的方法让增广运算符工作?在
您没有重写^{} method ,因此您的
c
是list
:这是一个即兴版本:
^{pr2}$相关问题 更多 >
编程相关推荐