2007/06/21

docstringとdoctest…Pythonのドキュメント?

pythonではクラス(メソッド)の説明を次のように書くらしい。
で、次のように書くとそれでテストもできるらしい。
>>> class test:
   """test class

   >>> test = test();
   initted
   >>> test.hello();
   HELLO
   """
   def __init__(self):
      """testclass's init"""
      print "initted";
   def hello(self):
      """print 'HELLO'"""
      print "HELLO";

>>> import doctest;
>>> doctest.testmod();
*** DocTestRunner.merge: '__main__.test.__init__' in both testers; summing outcomes.
*** DocTestRunner.merge: '__main__.test.hello' in both testers; summing outcomes.
*** DocTestRunner.merge: '__main__.doc' in both testers; summing outcomes.
*** DocTestRunner.merge: '__main__.test' in both testers; summing outcomes.
*** DocTestRunner.merge: '__main__' in both testers; summing outcomes.
(0, 2)

※上のはPython Shellでの入出力です。
宣言の直後にコメントを付ける。それがクラスを説明した文章で、docstringと呼ばれている。
docstringにはクラスの説明とクラスの宣言方法、使い方とその出力を記述する。
docstringにクラスの宣言方法、使い方を記述すると、doctestモジュールでテストが行える。
ただし、そのつど出力の変わるようなもののテストはできない。(現在時刻を表示するメソッドなど)

関連項目?

0 件のコメント: