Python
 Computer >> コンピューター >  >> プログラミング >> Python

Pythonでタイプをチェックするための標準的な方法は何ですか?


オブジェクト、xが正確に指定されたタイプ(サブタイプではない)のインスタンスであるかどうかを確認する場合は、typeを使用してそのタイプを取得し、isステートメントを使用して確認できます。

x = "Hello"
if type(x) is str:
   print("x is an instance of str")
出力 これにより出力が得られます

x is an instance of str

xがMyClassのインスタンスであるか、MyClassのサブクラスであるかを確認する場合は、isinstanceメソッド呼び出しを使用できます。

x = "Hello"
if isinstance(x, str):
   print("x is an instance of str")
出力 これにより出力が得られます

x is an instance of str

  1. 除数の数が偶数か奇数かをチェックするPythonプログラム

    この記事では、特定の問題ステートメントを解決するための解決策とアプローチについて学習します。 問題の説明 −数値「n」を指定して、除数の総数が偶数または奇数であることを確認します。 このアプローチでは、すべての除数を見つけて、除数の数が偶数または奇数であることを確認します。 実装は以下のとおりです- 例 import math def countDivisors(n) :    count = 0    # calculating all the divisors    root=int(math.sqrt(n))+2 &nbs

  2. Python例外をログに記録する最良の方法は何ですか?

    ロギングモジュールをインポートしてから、logging.exceptionメソッドを使用してPython例外のログを作成します。 例 import logging try: print 'toy' + 6 except Exception as e: logging.exception("This is an exception log") 出力 次の出力が得られます ERROR:root:This is an exception log Traceback (most recent call last): File "C:/Users/Tutor