2013-06-12 21 views
0

The fine manual沒有解決什麼str()方法提供三個參數的時候,我在此代碼找到了從requests/models.py做:提供三個參數時`str()`方法返回什麼?

content = str(self.content, encoding, errors='replace') 

這哪裏是記錄?它有什麼作用?

+0

內建的'str'函數只需要一個參數,可能是'models.py'中的類有它自己的'str'函數。 –

回答

3

您正在閱讀的文檔版本2,但使用閱讀代碼(或匹配)的Python 3

The docs for version 3說:

str(object='') 
str(object=b'', encoding='utf-8', errors='strict') 

Return a str version of object. See str() for details.

以下是說一下encoding和下面的鏈接errors關鍵字參數:

If at least one of encoding or errors is given, object should be a bytes -like object (e.g. bytes or bytearray). In this case, if object is a bytes (or bytearray) object, then str(bytes, encoding, errors) is equivalent to bytes.decode(encoding, errors) . Otherwise, the bytes object underlying the buffer object is obtained before calling bytes.decode() .

+0

謝謝。我正在運行Python 2代碼,所以我認爲我需要Python 2文檔。我應該說明。 – dotancohen

7

這不是內置str功能。看看imports at the top

from .compat import (
    cookielib, urlparse, urlunparse, urlsplit, urlencode, str, bytes, StringIO, 
    is_py2, chardet, json, builtin_str, basestring) 

肯尼斯已經定義了Python 2和3之間的兼容性自己compat模塊,他改變了幾個內建包括str

由於you can see in that module,在Python 2中,它的別名unicodestr,所以它幾乎和Python3 str一樣工作。

+0

謝謝。出於這個原因,當人們重寫內置函數時,我發現它很有問題。 – dotancohen

+0

我同意,但我明白他爲什麼在這種情況下做到了。 Django採用的另一種方法是使用'six'庫 - 但這意味着在任何地方調用'six.u()'等。 –

+0

對,只要作者希望成爲唯一一個處理代碼的人。平心而論,只要我決定「嗯,看看這件事情​​在做什麼可能是一個好主意」,我知道我一直處於一個受到傷害的世界。該庫本身是在我寫的應用程序中拋出Unicode錯誤:'File「/usr/lib/python2.7/dist-packages/requests/models.py」,行809,文本 content = str(self。內容,編碼,錯誤='替換') TypeError:unicode()參數2必須是字符串,而不是None。 – dotancohen

相關問題