2013-04-29 43 views
6
>>> print type(a) 
<type 'list'> 
>>> response.content = a 
>>> print type(response.content) 
<type 'str'> 

您能否向我解釋這個「魔法?」 a如何從list轉換爲stringREST響應內容如何「神奇地」從「列表」轉換爲「字符串」

responserest_framework.response.Response的實例。

+2

'some_object.some_variable'與'some_variable'有什麼關係?你能解釋一下這個好一點嗎? – mgilson 2013-04-29 19:11:37

+0

'type()'函數返回一個字符串,沒有任何轉換。 – 2013-04-29 19:11:54

+1

哪個魔法導致'some_object'出現被禁止? – 2013-04-29 19:12:09

回答

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) 
+4

https://github.com/django/django/blob/master/django/http/response.py#L282 – dm03514 2013-04-29 19:23:31

+1

@ dm03514 - 好吧,我想那時候會有答案。 :) – mgilson 2013-04-29 19:26:34

相關問題