Python Classes and Inheritance: week3

Test cases, edge cases

The test.testEqual Function

assert statement

Pythonにはassertという文があります。

assert の後に Python の式が続きます。

もしこの式が False と評価されたら、インタープリタは実行時エラーを発生させます。

もし式がTrueと評価されれば、何も起こらず、次の行のコードに進みます。

return value testsとside effect tests

  • Return a value. For these, you will write return value tests.
  • Modify the contents of some mutable object, like a list or dictionary. For these you will write side effect tests.
  • Print something or write something to a file. Tests of whether a function generates the right printed output are beyond the scope of this testing framework; you won’t write these tests.

side effect testはobjectがmutateされているかtsetする?

 

 extreme casesとtypical cases

 

What is an exception?

try:

から

except: まででエラーが出ても無視する?(except:だけでexcept するエラータイプを指定しないなら全てのエラーを対象とする。

エラーが起こった時点でexceptへ飛ぶ。

 

Some of the common Exception Errors are : 

  • IOError: if the file can’t be opened
  • KeyboardInterrupt: when an unrequired key is pressed by the user
  • ValueError: when built-in function receives a wrong argument
  • EOFError: if End-Of-File is hit without reading any data
  • ImportError: if it is unable to find the module
Python Try Except - GeeksforGeeks
A Computer Science portal for geeks. It contains well written, well thought and well explained computer science and prog...

Standard Exceptions

Runestone Interactive
Learning Python should be fun and easy. We provide an interactive Python textbook that helps you learn to program in Pyt...

あとindex errorも?

index がout of rangeになるタイプ

“try” clause

print(e)をかくと、エラーメッセージを出力してくれる。

errorが起こった時点で止まる仕組み

for statementの中でtry statementを使うとこうなる。

エラーが出るたびにリストにエラーを書き入れてくれる。エラーの原因をはつ件するのに役立ちそう。

testの紅葉?

try/exceptを使う理由は、コードを書いている時点では予測できない条件によって、正しく実行されるときとされないときがあるコードブロックがある場合です。

例えば、ウェブサイトからデータを取得するコードを実行しているとき、ネットワークに接続していないときや、外部のウェブサイトが一時的に応答しないときに、コードを実行することがあります。そのような状況でもプログラムが有用な処理を行えるのであれば、例外処理を行い、残りのコードを実行させたいと思うでしょう。

別の例として、あるWebサイトからネストされたデータを辞書dに取り込んだとする。特定の要素を抽出しようとすると、ある要素が欠落している可能性がある。特定のキーが存在しないことが予想される場合、if..elseチェックで対処することができます

if statementで発見しようとするには、ある程度エラーを予測する必要がある。

 

コメント