Python 关于UserList uuu init uuuuu的问题([:],isinstance)
我想用一些自定义方法扩展python37中的类列表。 最后读了那本书。阅读后,关于Python 关于UserList uuu init uuuuu的问题([:],isinstance),python,python-3.x,cpython,Python,Python 3.x,Cpython,我想用一些自定义方法扩展python37中的类列表。 最后读了那本书。阅读后,关于[:]用法出现了新的问题 如果我理解正确的话,`[:]`会制作一个整体的切片拷贝 `self.data`。但是我想知道使用“[:”有什么意义` 在“=”运算符的左侧 方案一和方案二有什么区别吗?在python中尝试 翻译,两者似乎都有相同的效果,我失踪了吗 什么 letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] # option (1) letters[:] = [] #
[:]
用法出现了新的问题
如果我理解正确的话,`[:]`会制作一个整体的切片拷贝
`self.data`。但是我想知道使用“[:”有什么意义`
在“=”运算符的左侧
方案一和方案二有什么区别吗?在python中尝试
翻译,两者似乎都有相同的效果,我失踪了吗
什么
letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
# option (1)
letters[:] = []
# option (2)
letters = []
现在是关于用户列表代码的问题。我用我的问题添加了评论
class UserList(_collections_abc.MutableSequence):
def __init__(self, initlist=None):
self.data = []
if initlist is not None:
if type(initlist) == type(self.data):
# NOTE: Is this if statement doing the same?
# if isinstance(initlist, list):
self.data[:] = initlist
# NOTE: wouldn't in this case self.data keep a reference to initlist
# instead of a copy?
# self.data[:] = initlist[:] # could one replace that line with this one?
elif isinstance(initlist, UserList):
self.data[:] = initlist.data[:]
# NOTE: would this line accomplish the same?
# self.data = initlist.data[:]
else:
self.data = list(initlist)
...
当您在=运算符的左侧指定a时,您使用的是Python的普通赋值,它将更改当前上下文中的名称a以指向新值。这不会更改a所指向的上一个值 通过在=运算符的左侧指定[0:2],可以告诉Python您想要使用切片分配。切片分配是列表的一种特殊语法,您可以在其中插入、删除或替换列表中的内容。 见:
也许这对你有帮助。如果你对
字母有另一个引用,它们的行为就不一样了
场景1:就地修改字母
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> lst = letters
>>> letters[:] = []
>>> letters
>>> []
>>> lst
>>> []
场景2,将名称字母重新分配到空列表
>>> letters = ['a', 'b', 'c', 'd', 'e', 'f', 'g']
>>> lst = letters
>>> letters = []
>>> letters
>>> []
>>> lst
>>> ['a', 'b', 'c', 'd', 'e', 'f', 'g']
因为,lst
没有看到任何更改
如果你有
self.data = initlist
突变到initlist
会影响self.data
(因为它们在内存中是相同的对象)。可能的重复