[英]Python what does self[name] = value means?
Python newbie here. Python新手在这里。 I am reading part of code from Taiga project which is based on Django. 我正在阅读基于Django的Taiga项目的部分代码。 I am having trouble to understand one line of the code. 我无法理解一行代码。
class Response(SimpleTemplateResponse):
def __init__(self, data=None, status=None,
template_name=None, headers=None,
exception=False, content_type=None):
super().__init__(None, status=status)
self.data = data
self.template_name = template_name
self.exception = exception
self.content_type = content_type
if headers:
for name, value in six.iteritems(headers):
self[name] = value
I don't quite understand the last line. 我不太明白最后一行。 self[name] = value. self [name] = value。 What does that exactly means? 这究竟意味着什么? Is that creating a dict? 这会创造一个字吗? If yes, how do I call this dict or make reference to this dict outside of the class? 如果是,我如何调用此词典或在课堂外引用此词典? If not, what does it do? 如果没有,它会做什么?
Taiga is based on django, which is where SimpleTemplateResponse
comes from. Taiga基于django,这是SimpleTemplateResponse
来源。 It is a subclass of HttpResponse
which is a dict-like object. 它是HttpResponse
的子类,它是一个类似dict的对象。
Now, the loop is checking first if there is a name headers
that is not None, or False. 现在,循环首先检查是否存在非None或False的名称headers
。 If it is set, then it is assuming that headers
is a dictionary, and looping through each key/value pair of the dictionary with iteritems. 如果设置了,则假设headers
是字典,并使用iteritems循环遍历字典的每个键/值对。 It then duplicates the same keys and values as properties of the class, with self[name] = value
. 然后它使用self[name] = value
复制与类的属性相同的键和值。
In effect, what this means is that if there is are headers, they are accessible directly in the class as keys. 实际上,这意味着如果有标题,则可以在类中直接访问它们作为键。
Here is a simple example of what its doing: 这是一个简单的例子:
>>> class MyFoo(object):
... def __init__(self):
... self._data = {}
... def __setitem__(self, a, b):
... self._data[a] = b
... def __getitem__(self, a):
... return self._data[a]
... def __delitem__(self, a):
... del self._data[a]
... def populate(self, d):
... if d:
... for k,v in d.iteritems():
... self[k] = v
...
>>> headers = {'User-Agent': 'Python/2.7.5'}
>>> a = MyFoo()
>>> a.populate(headers)
>>> a['User-Agent']
'Python/2.7.5'
You can see that MyFoo
is a simple class, but it defines some special methods __setitem__
, __getitem__
, __delitem__
. 你可以看到, MyFoo
是一个简单的类,但它定义了一些特殊的方法__setitem__
, __getitem__
, __delitem__
。 These methods let any object of the class act like a dictionary. 这些方法让类的任何对象都像字典一样。
The populate
method is doing what is being done in the loop in the original source; populate
方法正在执行原始源中循环中正在执行的操作; and once its run - all keys of the dictionary become keys of the resulting MyFoo
object. 一旦运行 - 字典的所有键都成为生成的MyFoo
对象的键。
In the source of the HttpResponse class you'll note the same __setitem__
, __getitem__
, __delitem__
are defined (scroll down to line 140 ). 在HttpResponse类的源代码中,您将注意到相同的__setitem__
__getitem__
, __delitem__
__getitem__
, __delitem__
已定义(向下滚动到第140行 )。
Response
class is implementing sequence protocol. Response
类正在实现序列协议。 That's It'll be having __setitem__
and __getitem__
magic methods defined in it, which will make it to behave like any sequence or dictionary. 那就是它将在其中定义__setitem__
和__getitem__
魔术方法,这将使其表现得像任何序列或字典。
In Django
HttpResponse has been implemented as a container ( HTTP response class with dictionary-accessed headers
) 在Django
HttpResponse已经实现为一个容器( HTTP response class with dictionary-accessed headers
)
More about containers.. 更多关于容器..
In Python
one can create a container objects by implementing certain magic methods.. 在Python
可以通过实现某些魔术方法来创建容器对象。
A sample container for better understanding.. 样品容器,以便更好地理解..
>>> 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]
...
Since we've implemented __setitem__
for assiginment
and __getitem__
for get
and __delitem__
for deleting an item
, now Container
object supports all these three operations.. 既然我们已经实现__setitem__
为assiginment
和__getitem__
为get
和__delitem__
为deleting an item
,现在Container
对象支持所有这三种操作方法。
Assigning
value to some attribute for Container object.. 为Container对象的某个属性Assigning
。
>>> obj = Container()
>>> obj[1] = 'Assigned 1'
Setitem called for assignment!
When ever we try to assign something to this container by calling like obj[--some_attr--] = value
, python checks for __setitem__
method for this class and it's developers duty to write their own logic where to store that values, whether it's a dict or some other data structure.. 当我们尝试通过调用obj[--some_attr--] = value
为这个容器obj[--some_attr--] = value
,python会检查这个类的__setitem__
方法,并且开发人员有责任编写自己的逻辑来存储这些值,无论是否为字典或其他一些数据结构..
Retrieving
a value from the container... 从容器中Retrieving
值...
>>> obj[1]
Getitem called for retrieving!
'Assigned 1'
When ever we try to retrieve something to from container by calling like obj[--some_attr--]
, python checks for __getitem__
method for this object and it's developers duty to write their own logic to return or do some operation inside.. 当我们尝试通过调用obj[--some_attr--]
从容器中检索某些内容时,python会检查此对象的__getitem__
方法,并且开发人员有责任编写自己的逻辑来返回或在内部执行某些操作。
Delete
value from the container.. 从容器中Delete
值..
>>> del obj[1]
Delitem called for deleting item!
When ever we try to delete something to from container by calling like del obj[--some_attr--]
, python checks for __delitem__
method for this object... 当我们尝试通过调用del obj[--some_attr--]
从容器中删除某些内容时,python会检查此对象的__delitem__
方法...
So where ever you see self[item] = value
or self[item]
or del self[item]
is same as doing this with object. 所以你在哪里看到self[item] = value
或self[item]
或del self[item]
与使用object执行此操作相同。
Your SimpleTemplateResponse
object (the parent class of Response
) will have a __getitem__
and a __setitem__
method. 您的SimpleTemplateResponse
对象( Response
的父类)将具有__getitem__
和__setitem__
方法。
I don't know what the __getitem__
or __setitem__
methods that are inherited from SimpleTemplateResponse
will do, but I'm guessing that, in this case, it will return an attribute of a response object. 我不知道从SimpleTemplateResponse
继承的__getitem__
或__setitem__
方法会做什么,但我猜测,在这种情况下,它将返回响应对象的属性。
Essentially what you're doing is setting a particular attribute of the Response
object to the value based on the rules in the inherited __getitem__
and __setitem__
methods. 基本上你正在做的是根据继承的__getitem__
和__setitem__
方法中的规则将Response
对象的特定属性设置为值。
A python class is behaving like a dictionary. python类的行为类似于字典。 When you do: self["foo"] = 1234 You can access it like a normal attribute of self: print(self.foo) The same holds for functions. 当你这样做:self [“foo”] = 1234你可以像self的普通属性一样访问它:print(self.foo)同样适用于函数。 It is used to dynamically extend a class. 它用于动态扩展类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.