簡體   English   中英

將多個調用分配給單個變量,否則對性能無關緊要

[英]Assign multiple calls to a single variable or it does not matter for performance-wise

示例#1:

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')

示例#2:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM