在檢查array
是否是您的文檔字符串應該是,我不會打擾。使用duck typing;假設這是正確的事情,並讓調用者處理任何錯誤,如果他們不通過你所要求的。
如果輸入無效,則您的函數無法繼續,因此沒有意義處理該級別的錯誤,並嘗試明確使用例如isinstance
只能縮小用戶可以進一步傳遞的內容(例如,如果用戶傳入元組元組而不是列表列表,它們爲什麼不能繼續工作?它們都是序列... )。
如果您的問題實際上是關於包括示例,爲您的評論表明,這裏就是我會開始:
def is_magic(array):
"""Whether the array is 'magic'.
Arguments:
array (sequence of sequences of integers): The array to test.
Returns:
bool: Whether the array is 'magic'.
Notes:
A 'magic' array is a 3x3 array of integers where each row, column
and diagonal adds up to the same number
Examples:
>>> is_magic([[8, 3, 4], [1, 5, 9], [6, 7, 2]])
True
"""
raise NotImplementedError
if __name__ == '__main__':
import doctest
doctest.testmod()
的docstring文檔的功能,並且可以通過例如使用IDE和help
函數來告訴用戶該功能的功能。請注意使用doctest
示例,這兩個示例都向用戶顯示如何調用函數以及返回期望的內容,並充當代碼的測試。
當然,當你第一次運行它,它就會失敗......
**********************************************************************
File "C:\Python27\so.py", line 16, in __main__.is_magic
Failed example:
is_magic([[8, 3, 4], [1, 5, 9], [6, 7, 2]])
Exception raised:
Traceback (most recent call last):
File "C:\Python27\lib\doctest.py", line 1315, in __run
compileflags, 1) in test.globs
File "<doctest __main__.is_magic[0]>", line 1, in <module>
is_magic([[8, 3, 4], [1, 5, 9], [6, 7, 2]])
File "C:\Python27\so.py", line 20, in is_magic
raise NotImplementedError
NotImplementedError
**********************************************************************
1 items had failures:
1 of 1 in __main__.is_magic
***Test Failed*** 1 failures.
* 「型合同」 *?這是* Python!*假設輸入是一系列序列,並讓調用者處理任何錯誤,如果他們通過其他任何東西。 – jonrsharpe
@jonrsharpe但我將不得不輸入的例子,如果我放在讓我們說is_magic( .....),然後把它假設的輸出。 – JerryMichaels
如果你想展示的例子,把它們放在docstring中['doctest's](https://docs.python.org/3/library/doctest.html),那麼你實際上可以確保它們運行並使用它們測試你的代碼。 – jonrsharpe