栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

i = i + n是否真的与i + = n相同?[重复]

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

i = i + n是否真的与i + = n相同?[重复]

它们不必相同。

使用

+
运算符调用方法,
__add__
而使用
+=
运算符调用
__iadd__
。完全取决于所讨论的对象,当调用这些方法之一时会发生什么。

如果使用

x += y
x
不提供
__iadd__
方法(或方法返回
NotImplemented
),
__add__
则用作 后备
,即
x = x + y
会发生这种情况。

对于列表,使用

l +=iterable
实际
l
使用的元素扩展列表
iterable
。在您的情况下,字符串(可迭代)中的每个字符都会在
extend
操作过程中附加。

演示1:使用

__iadd__

>>> l = []>>> l += 'table'>>> l['t', 'a', 'b', 'l', 'e']

演示2:使用方法

extend
相同

>>> l = []>>> l.extend('table')>>> l['t', 'a', 'b', 'l', 'e']

演示3:添加列表和字符串会引发

TypeError

>>> l = []>>> l = l + 'table'[...]TypeError: can only concatenate list (not "str") to list

不使用

+=
将为您提供
TypeError
这里的信息,因为仅
__iadd__
实现了扩展行为。

演示4:常见陷阱:

+=
不建立新列表。我们可以通过与
is
操作员检查相同的对象身份来确认这一点。

>>> l = []>>> l_ref = l # another name for l, no data is copied here>>> l += [1, 2, 3] # uses __iadd__, mutates l in-place>>> l is l_ref # confirm that l and l_ref are names for the same objectTrue>>> l[1, 2, 3]>>> l_ref # mutations are seen across all names[1, 2, 3]

但是,

l = l + iterable
语法确实会建立一个新列表。

>>> l = []>>> l_ref = l # another name for l, no data is copied here>>> l = l + [1, 2, 3] # uses __add__, builds new list and reassigns name l>>> l is l_ref # confirm that l and l_ref are names for different objectsFalse>>> l[1, 2, 3]>>> l_ref[]

在某些情况下,这可能会产生细微的错误,因为会

+=
更改 原始列表,同时
l = l + iterable
会构建 列表并 重新分配 名称
l

奖金

Ned
Batchelder在文档中找到这个的挑战



转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/668107.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号