[英]Python “in-place” reassignment of a mutable object in the absence of setter methods
[英]In-place methods in subclasses
我正在尝试对list
进行子类化,以便创建一个就地方法,该方法使用self和新列表的逐项总和更新self
。 例子:
这就是我尝试这样做的方式:
class RecordBook(list):
def accumulate(self, new_values):
self = RecordBook([x+y for x, y in zip(self, new_values)])
尽管重新绑定回self
将就地修改它。 但是它不起作用。
>> d = RecordBook([1, 2, 3, 4, 5, 6])
>> d
[1, 2, 3, 4, 5, 6]
>> d.accumulate([1]*6)
>> d
[1, 2, 3, 4, 5, 6] # should have been [2, 3, 4, 5, 6, 7]
为什么这会导致任务失败,人们将如何解决这个问题?
这是将collections.UserList
子类化并修改子类的底层self.data
的一种方法。
正如@Deceze 在评论中所解释的:
self 只是一个局部变量,为它分配其他东西不会替换现有对象
UserList
公开可以“就地”修改的self.data
属性
from collections import UserList
class Accumulator(UserList):
def accumulate(self, seq):
for idx, elt in enumerate(seq):
self.data[idx] += elt
if __name__ == '__main__':
d = Accumulator([1, 2, 3, 4, 5, 6])
d.accumulate([1]*6)
print(d)
[2, 3, 4, 5, 6, 7]
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.