Bob*_*ble 0 python list subclass operators
我最初将它实现为一个包含在列表中的包装类,但我对我需要提供的operator()方法的数量感到恼火,所以我只是简单地继承了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)
Run Code Online (Sandbox Code Playgroud)
正常的加法和减法以预期的方式工作,但是增强的加法和减法存在问题.这是输出:
>>>
CleverList does vector arith: a, b, a+b, a-b = [0, 1] [3, 4] [3, 5] [-3, -3]
clone test: e = a[:]: a, e = [0, 1] [0, 1]
OOPS: augmented addition: c += a: a, c = [0, 1] [0, 1, 0, 1]
Traceback (most recent call last):
File "/home/bob/Documents/Python/listTest.py", line 35, in <module>
c -= b
TypeError: unsupported operand type(s) for -=: 'list' and 'CleverList'
>>>
Run Code Online (Sandbox Code Playgroud)
是否有一种简洁的方法可以让增强运算符在这个例子中工作?
你没有覆盖__getslice__
方法,所以你c
是list
:
>>> a = CleverList([0, 1])
>>> a
[0, 1]
>>> type(a)
<class '__main__.CleverList'>
>>> type(a[:])
<type 'list'>
Run Code Online (Sandbox Code Playgroud)
这是一个袖手旁观的版本:
def __getslice__(self, *args, **kw):
return self.__class__(super(CleverList, self).__getslice__(*args, **kw))
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
844 次 |
最近记录: |