>>> print type(a)
<type 'list'>
>>> response.content = a
>>> print type(response.content)
<type 'str'>
你能给我解释一下这个“魔法”吗?如何a
从 转换list
为string
?
response
是 的一个实例rest_framework.response.Response
。
只有几种方法可以让这样的事情发生。最常见的原因是如果response.content
被实现为某种描述符,可能会发生类似这样的有趣事情。(像这样操作的典型描述符是一个property
对象)。在这种情况下,属性的 getter 将返回一个字符串。作为一个正式的例子:
class Foo(self):
def __init__(self):
self._x = 1
@property
def attribute_like(self):
return str(self._x)
@attribute_like.setter
def attribute_like(self,value):
self._x = value
f = Foo()
f.attribute_like = [1,2,3]
print type(f.attribute_like)
我想这个类是通过定义__setattr__
方法进行这种转换的。您可以阅读http://docs.python.org/2.7/reference/datamodel.html#customizing-attribute-access了解更多信息。