下面是一个类,用于保存列表,并向列表中添加提供给它的任何新值(以及能够打印列表):
class foobar:
def __init__(self, value=None):
if type(value) is str:
self.value = [value]
else:
self.value = ['']
def __iadd__(self, new_value):
self.value.append(new_value)
def add(self, new_value):
self.value.append(new_value)
def __str__(self):
return str(self.value)
函数add
仅用于测试目的
这个问题是,对象的两个函数add
和__iadd__()
的行为并不相同。或者我是这么想的
实际上,上面提到的两个函数确实产生相同的结果,但是add
和+=
产生不同的结果
运行示例:
>>> testStr = foobar()
>>> testStr
<__main__.foobar instance at 0x00000000034CCE48>
>>> print testStr
['']
>>> testStr.add('val1')
>>> testStr
<__main__.foobar instance at 0x00000000034CCE48>
>>> print testStr
['', 'val1']
>>> testStr.__iadd__('val2')
>>> testStr
<__main__.foobar instance at 0x00000000034CCE48>
>>> print testStr
['', 'val1', 'val2']
>>> testStr += 'val3'
>>> testStr
>>> print testStr
None
正如您所看到的,+=
操作将foobar
的testStr
实例转换为NoneType
,因此(显然)删除了其中包含的值
我的理解是__iadd__()
和+=
操作符的行为应该是相同的,但似乎不是这样。这里是否可以实现__iadd__()
以适当地更新+=
的行为,或者这种类型的操作是否存在问题
__iadd__
必须返回更新的对象(可以是self
):您没有返回任何内容,因此使用了默认返回值
None
从^{} documentation 开始:
大胆强调地雷;注意
x = x.__iadd__(y)
等价性相关问题 更多 >
编程相关推荐