为包含lis的对象重载

2024-09-27 04:25:49 发布

您现在位置:Python中文网/ 问答频道 /正文

下面是一个类,用于保存列表,并向列表中添加提供给它的任何新值(以及能够打印列表):

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

正如您所看到的,+=操作将foobartestStr实例转换为NoneType,因此(显然)删除了其中包含的值

我的理解是__iadd__()+=操作符的行为应该是相同的,但似乎不是这样。这里是否可以实现__iadd__()以适当地更新+=的行为,或者这种类型的操作是否存在问题


Tags: instance函数selfadd列表newvaluemain
1条回答
网友
1楼 · 发布于 2024-09-27 04:25:49

__iadd__必须返回更新的对象(可以是self):

def __iadd__(self, new_value):
    self.value.append(new_value)
    return self

您没有返回任何内容,因此使用了默认返回值None

^{} documentation开始:

These methods should attempt to do the operation in-place (modifying self) and return the result (which could be, but does not have to be, self). [...] For instance, if x is an instance of a class with an __iadd__() method, x += y is equivalent to x = x.__iadd__(y).

大胆强调地雷;注意x = x.__iadd__(y)等价性

相关问题 更多 >

    热门问题