[英]Assign multiple calls to a single variable or it does not matter for performance-wise
import requests
r_get_obj = requests.get('http://localhost')
r__get__content = r_get_obj.text
if 'junior' in r__get__content:
print('junior')
elif 'egg' in r__get__content:
print('egg')
else:
print('none')
import requests
r_get_obj = requests.get('http://localhost')
if 'junior' in r_get_obj.text:
print('junior')
elif 'egg' in r_get_obj.text:
print('egg')
else:
print('none')
如您所見,示例 1將請求內容分配給一個變量,然后使用它進行檢查,
但是示例 2沒有將其分配給變量而是繼續調用r_get_obj.text
。
我的問題是,第二個是否有不良的性能影響/不良的非干凈代碼,哪一個是首選?
您可以在requests
庫中進行快速潛水和研究,以得出您應該做什么的結論。 請注意以下幾點:
resp = requests.get("http://google.com")
type(resp)
輸出:
<class 'requests.models.Response'>
在他們的 repo ( requests/models.py
) 中進入該類,您最終會看到名為Response
的類定義:
class Response(object):
"""The :class:`Response <Response>` object, which contains a
server's response to an HTTP request.
"""
...
向下滾動你會注意到一個名為text
的屬性方法,它是你正在調用的方法:
...
@property
def text(self):
"""Content of the response, in unicode.
If Response.encoding is None, encoding will be guessed using
``chardet``.
The encoding of the response content is determined based solely on HTTP
headers, following RFC 2616 to the letter. If you can take advantage of
non-HTTP knowledge to make a better guess at the encoding, you should
set ``r.encoding`` appropriately before accessing this property.
"""
...
此方法在每次返回結果(和預期) text
變量之前進行一些編碼; 也就是說,它沒有緩存。 在這種情況下,最好自己簡單地緩存它,而不必擔心(abuit,次要)性能問題:
resp = requests.get("http://google.com")
html = resp.text
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.