isinstance() で確認する
このステップでは、Python の isinstance() 関数を使って、オブジェクトが特定のクラスのインスタンスであるかどうかをチェックする方法を学びます。これは、変数がブール値を保持しているかどうかを確認する別の方法です。isinstance() 関数は 2 つの引数を取ります。チェックするオブジェクトと、比較するクラスです。オブジェクトがクラスのインスタンスであれば True を返し、そうでなければ False を返します。
isinstance() を使って、変数がブール型であるかどうかをチェックしてみましょう。
-
VS Code エディタを使って、~/project ディレクトリの boolean_example.py ファイルを開きます。
-
boolean_example.py ファイルを編集して、isinstance() 関数を追加します。
## Assign True to a variable
is_active = True
## Assign False to a variable
is_admin = False
## Print the values
print("Is active:", is_active)
print("Is admin:", is_admin)
## Comparison operations
x = 10
y = 5
is_greater = x > y ## True because 10 is greater than 5
is_equal = x == y ## False because 10 is not equal to 5
print("Is x greater than y:", is_greater)
print("Is x equal to y:", is_equal)
## Check the types of the variables
print("Type of is_active:", type(is_active))
print("Type of is_greater:", type(is_greater))
print("Type of x:", type(x))
## Check if the variables are instances of the bool class
print("is_active is an instance of bool:", isinstance(is_active, bool))
print("x is an instance of bool:", isinstance(x, bool))
-
ファイルを保存します。
-
ターミナルで python コマンドを使ってスクリプトを実行します。
python ~/project/boolean_example.py
以下のような出力が表示されるはずです。
Is active: True
Is admin: False
Is x greater than y: True
Is x equal to y: False
Type of is_active: <class 'bool'>
Type of is_greater: <class 'bool'>
Type of x: <class 'int'>
is_active is an instance of bool: True
x is an instance of bool: False
ご覧の通り、isinstance(is_active, bool) は is_active がブール値であるため True を返し、isinstance(x, bool) は x が整数であるため False を返します。isinstance() 関数は、変数が特定のクラスに属しているかどうかをチェックするのに便利で、データ型を検証するより堅牢な方法を提供します。