Python學習筆記__8.4章 文檔測試

來源:互聯網
上載者:User

標籤:程式設計語言   Python   

# 這是學習廖雪峰老師python教程的學習筆記

1、概覽

在文檔中編寫規範的注釋代碼。則Python內建的“文檔測試”(doctest)模組可以直接提取注釋中的代碼並執行測試。

1.1、以abs()函數為例:

#abs.py

def abs(n):

    ''' # 兩個為一對,換行輸入

    Function to get absolute value of number.  # 簡單的介紹

 

    Example:

 

    >>> abs(1)   # 測試

    1

    >>> abs(-1)

    1

    >>> abs(0)

    0

    '''  #

    return n if n >= 0 else (-n)  # 函數體

$ python abs.py  # 命令列執行程式,無傳回值,則代碼無誤

 

1.2、doctest來測試上次編寫的Dict類

# mydict2.py

class Dict(dict):

    '''

    Simple dict but also support access as x.y style.

 

    >>> d1 = Dict()

    >>> d1['x'] = 100

    >>> d1.x

    100

    >>> d1.y = 200

    >>> d1['y']

    200

    >>> d2 = Dict(a=1, b=2, c='3')

    >>> d2.c

    '3'

    >>> d2['empty']

    Traceback (most recent call last):

        ...  # 這三個.表示一大段輸出

    KeyError: 'empty'

    >>> d2.empty

    Traceback (most recent call last):

        ...

    AttributeError: 'Dict' object has no attribute 'empty'

    '''

    def __init__(self, **kw):

        super(Dict, self).__init__(**kw)

 

    def __getattr__(self, key):

        try:

            return self[key]

        except KeyError:

            raise AttributeError(r"'Dict' object has no attribute '%s'" % key)

 

    def __setattr__(self, key, value):

        self[key] = value

 

if __name__=='__main__':

    import doctest

    doctest.testmod()

 

總結:

doctest非常有用,不但可以用來測試,還可以直接作為範例程式碼。通過某些文檔產生工具,就可以自動把包含doctest的注釋提取出來。使用者看文檔的時候,同時也看到了doctest。


Python學習筆記__8.4章 文檔測試

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.