6
>>> print type(a)
<type 'list'>
>>> response.content = a
>>> print type(response.content)
<type 'str'>

你能给我解释一下这个“魔法”吗?如何a从 转换liststring

response是 的一个实例rest_framework.response.Response

4

2 回答 2

8

只有几种方法可以让这样的事情发生。最常见的原因是如果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)
于 2013-04-29T19:22:36.863 回答
2

我想这个类是通过定义__setattr__方法进行这种转换的。您可以阅读http://docs.python.org/2.7/reference/datamodel.html#customizing-attribute-access了解更多信息。

于 2013-04-29T19:23:12.347 回答