99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀普通青年加注釋,文藝青年用docstring
普通青年加注釋,文藝青年用docstring
2022-03-16
收藏
普通青年加注釋,文藝青年用docstring

作者:麥?zhǔn)?/span>

來源:麥?zhǔn)寰幊?/span>

我對注釋的態(tài)度

加注釋無疑是很好的習(xí)慣,但是有時候會被濫用。我一直持有以下幾個觀點:

  • 最好的注釋是代碼,把代碼寫清晰是首要的,是程序員最重要的修煉。
  • 注釋應(yīng)該言簡意賅,不是越多越好。修改了代碼后,要對注釋做相應(yīng)的修改,否則會給閱讀者產(chǎn)生誤導(dǎo)。
  • Python的方法總體解釋,應(yīng)該使用docstring,不要使用注釋。方法體內(nèi)必要的地方可以注釋。

docstring

先來看看什么是docstring

  • docstring是在類的第一行或者方法的第一行添加的用于解釋類或者方法的字符串
  • docstring必須用三引號,可以是單引號,也可以是雙引號,但必須是三引號。
  • docstring可以自動生成Python文檔,可以使用help()函數(shù)查看。

所以docstring是注釋,但又不是普通的注釋,可以說它具有一定的語義,可以被pythonhelp()函數(shù)或者其他代碼識別。這些都是注釋所不具備的。

看個例子

要編寫更好的代碼,最好的習(xí)慣之一是看內(nèi)置庫的源代碼。這些代碼通常都是很經(jīng)典的。

我們來看看random庫的部分源代碼:

class Random(_random.Random): """Random number generator base class used by bound module functions.

    Used to instantiate instances of Random to get generators that don't
    share state.

    Class Random can also be subclassed if you want to use a different basic
    generator of your own devising: in that case, override the following
    methods:  random(), seed(), getstate(), and setstate().
    Optionally, implement a getrandbits() method so that randrange()
    can cover arbitrarily large ranges.

    """ VERSION = 3 # used by getstate/setstate def __init__(self, x=None): """Initialize an instance.

        Optional argument x controls seeding, as for Random.seed().
        """ self.seed(x)
        self.gauss_next = None def seed(self, a=None, version=2): """Initialize internal state from a seed.

        The only supported seed types are None, int, float,
        str, bytes, and bytearray.

        None or no argument seeds from current time or from an operating
        system specific randomness source if available.

        If *a* is an int, all bits are used.

        For version 2 (the default), all of the bits are used if *a* is a str,
        bytes, or bytearray.  For version 1 (provided for reproducing random
        sequences from older versions of Python), the algorithm for str and
        bytes generates a narrower range of seeds.

        """ if version == 1 and isinstance(a, (str, bytes)):
            a = a.decode('latin-1') if isinstance(a, bytes) else a
            x = ord(a[0]) << 7 if a else 0 for c in map(ord, a):
                x = ((1000003 * x) ^ c) & 0xFFFFFFFFFFFFFFFF x ^= len(a)
            a = -2 if x == -1 else x elif version == 2 and isinstance(a, (str, bytes, bytearray)): if isinstance(a, str):
                a = a.encode()
            a = int.from_bytes(a + _sha512(a).digest(), 'big') elif not isinstance(a, (type(None), int, float, str, bytes, bytearray)):
            _warn('Seeding based on hashing is deprecatedn' 'since Python 3.9 and will be removed in a subsequent ' 'version. The only n' 'supported seed types are: None, ' 'int, float, str, bytes, and bytearray.',
                  DeprecationWarning, 2)

        super().seed(a)
        self.gauss_next = None def getstate(self): """Return internal state; can be passed to setstate() later.""" return self.VERSION, super().getstate(), self.gauss_next def setstate(self, state): """Restore internal state from object returned by getstate().""" version = state[0] if version == 3:
            version, internalstate, self.gauss_next = state
            super().setstate(internalstate) elif version == 2:
            version, internalstate, self.gauss_next = state # In version 2, the state was saved as signed ints, which causes #   inconsistencies between 32/64-bit systems. The state is #   really unsigned 32-bit ints, so we convert negative ints from #   version 2 to positive longs for version 3. try:
                internalstate = tuple(x % (2 ** 32) for x in internalstate) except ValueError as e: raise TypeError from e
            super().setstate(internalstate) else: raise ValueError("state with version %s passed to " "Random.setstate() of version %s" %
                             (version, self.VERSION))

類的開頭,和方法的開頭都有大段的docstring。

docstring的兩個用法:

我們來試一下docstring的使用。

__doc__屬性

打開命令行窗口,進入交互式Python。

如下所示,可以看到,我們寫的docstring自動成為了一個名為__doc__的屬性:

這個屬性任何類或函數(shù)都有,只不過有的為空。

>>> import random
>>> random.__doc__
'Random variable generators.nn    bytesn    -----n           uniform bytes (values between 0 and 255)nn    integersn    --------n           uniform within rangenn    sequencesn    ---------n           pick random elementn           pick random samplen           pick weighted random samplen           generate random permutationnn    distributions on the real line:n    ------------------------------n           uniformn           triangularn           normal (Gaussian)n           lognormaln           negative exponentialn           gamman           betan           pareton Weibullnn    distributions on the circle (angles 0 to 2pi)n    ---------------------------------------------n           circular uniformn           von MisesnnGeneral notes on the underlying Mersenne Twister core generator:nn* The period is 2**19937-1.n* It is one of the most extensively tested generators in existence.n* The random() method is implemented in C, executes in a single Python step,n  and is, therefore, threadsafe.nn'
普通青年加注釋,文藝青年用docstring

help()函數(shù)

docstring的第二個用法是,可以用help()函數(shù)打印出來。如下所示:

Python 3.10.0 (v3.10.0:b494f5935c, Oct 4 2021, 14:59:19) [Clang 12.0.5 (clang-1205.0.22.11)] on darwin
Type "help", "copyright", "credits" or "license" for more information. >>> import random >>> help(random)

這時候屏幕就會展示random模塊的docstring,這正是上面代碼中的三引號括起來的那一大段:

普通青年加注釋,文藝青年用docstring

普通青年寫注釋,文藝青年用docstring。下一次寫類,寫函數(shù)的時候,嘗試使用docstring,而不是使用注釋吧。

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }