Python 2.7 为什么在更改列表类型数据时不调用_usetItem _uu?
在下面的示例中,如果通过Python 2.7 为什么在更改列表类型数据时不调用_usetItem _uu?,python-2.7,Python 2.7,在下面的示例中,如果通过=设置数据,则有一个类的\uuuu setitem\uuu-方法可以正常工作。但是,如果使用.append-方法隐式设置了类型为list的实例数据,则不会调用\uuuuuuuuu setitem\uuuuu-方法。是否有某种方法可以确保在设置或修改数据时调用\uuuuu setitem\uuuuuuuuuuuuuuu(或类似“\uuuuuuuuu moditem\uuuuuuuuu”)之类的内容 class MyClass(object): data = {}
=
设置数据,则有一个类的\uuuu setitem\uuu
-方法可以正常工作。但是,如果使用.append
-方法隐式设置了类型为list
的实例数据,则不会调用\uuuuuuuuu setitem\uuuuu
-方法。是否有某种方法可以确保在设置或修改数据时调用\uuuuu setitem\uuuuuuuuuuuuuuu
(或类似“\uuuuuuuuu moditem\uuuuuuuuu
”)之类的内容
class MyClass(object):
data = {}
def __setitem__(self, key, value):
self.data[key] = value
print "I do not like change."
def __getitem__(self, item):
return self.data[item]
c = MyClass()
c['list'] = ['hello'] #does invoke setitem
c['list'].append('world') #does not invoke __setitem__
处理这个问题的适当方法是什么?当然,最后一行可以替换为
c['list'] = c['list'] + ['world']
但是,如果此类位于类库中,用户可能不知道:/
\uuuuu setitem\uuuuuu
在改变容器本身时调用,而不是在改变包含的元素时调用。容器无法监视它所容纳的项目何时发生更改。毕竟,请考虑这个代码:
c = MyClass()
c['list'] = ['hello'] # Invokes setitem
foo = c['list'] # Grabs a reference to the object just put into the container
foo.append('world') # setitem is, of course, not invoked
如果您发现自己想要这样做,那么您可能希望容器保存(或者至少返回)的不是标准的列表类型和诸如此类的内容,而是向中央数据存储报告的代理。
xml.etree
模块就是这类事情的一个很好的例子。\uuuuuu setitem\uuuuu
仅通过以下语法调用:
obj[key] = value # this equals to obj.__setitem__(key, value)
在其他情况下,当您使用obj[key]
\uuuu getitem\uuuuu
时,将调用
例如:
class MyClass(object):
data = {}
def __setitem__(self, key, value):
self.data[key] = value
print "__setitem__ called"
def __getitem__(self, item):
print "__getitem__ called"
return self.data[item]
c = MyClass()
c['list'] = ['hello'] # __setitem__ called
c['list'].append('world') # __getitem__ called
换句话说,在使用c['list']的最后一行中,首先调用\uuu getitem\uuu
,它返回指向上面初始化的列表['hello']的指针。然后,调用该点的append
方法