>>> print type(a)
<type 'list'>
>>> response.content = a
>>> print type(response.content)
<type 'str'>
您能否向我解釋這個「魔法?」 a
如何從list
轉換爲string
?REST響應內容如何「神奇地」從「列表」轉換爲「字符串」
response
是rest_framework.response.Response
的實例。
>>> print type(a)
<type 'list'>
>>> response.content = a
>>> print type(response.content)
<type 'str'>
您能否向我解釋這個「魔法?」 a
如何從list
轉換爲string
?REST響應內容如何「神奇地」從「列表」轉換爲「字符串」
response
是rest_framework.response.Response
的實例。
我想這個類通過定義__setattr__
方法進行這種轉換。你可以閱讀http://docs.python.org/2.7/reference/datamodel.html#customizing-attribute-access瞭解更多信息。
哦,對。我想有兩種方法。 '__setattr__'(可能帶有'__getattr__')/'__getattribute__'或描述符。 – mgilson 2013-04-29 19:25:32
只有幾種方法可以讓你發生這樣的事情。最常見的原因是,如果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)
'some_object.some_variable'與'some_variable'有什麼關係?你能解釋一下這個好一點嗎? – mgilson 2013-04-29 19:11:37
'type()'函數返回一個字符串,沒有任何轉換。 – 2013-04-29 19:11:54
哪個魔法導致'some_object'出現被禁止? – 2013-04-29 19:12:09