在Django中,HttpResponse被实现为一个容器(HTTP response class with dictionary-accessed headers)

有关容器的详细信息。。在

在Python中,可以通过实现某些魔术方法来创建container对象。。在

为了更好地理解。。在>>> class Container(object):

... def __init__(self):

... self.d = {}

... def __setitem__(self, i, k):

... print 'Setitem called for assignment!'

... self.d[i] = k

... def __getitem__(self, i):

... print 'Getitem called for assignment!'

... return self.d[i]

... def __delitem__(self, i):

... print 'Delitem called for assignment!'

... del self.d[i]

...

因为我们已经为assiginment实现了__setitem__,为get实现了{},为deleting an item实现了{},现在{}对象支持这三个操作。。在

Assigning值转换为容器对象的某个属性。。在

^{pr2}$

当我们试图通过调用obj[--some_attr--] = value来为这个容器赋值时,python会检查这个类的__setitem__方法,开发人员有责任编写自己的逻辑来存储这些值,不管它是dict还是其他数据结构。。在

Retrieving容器中的值。。。在>>> obj[1]

Getitem called for retrieving!

'Assigned 1'

当我们试图通过调用obj[--some_attr--]从容器中检索到某个对象时,python会检查该对象的__getitem__方法,开发人员有责任编写自己的逻辑来返回或在其中执行一些操作。。在

来自容器的Delete值。。在>>> del obj[1]

Delitem called for deleting item!

当我们试图通过调用del obj[--some_attr--]从容器中删除某个对象时,python会检查该对象的__delitem__方法。。。在

所以,无论你在哪里看到self[item] = value或{}或{}都与对object做同样的操作。在

更多推荐

python中的value是什么意思_Python self[name]=value是什么意思?