type関数の使い方(オブジェクトの型を取得する)

Python で用意されている組み込み関数の中の type 関数の使い方です。 type 関数はオブジェクトのデータ型を取得します。

(Last modified: )

type関数の書式と基本的な使い方

type 関数は引数に指定したオブジェクトのデータ型を表す型オブジェクトを返します。 type 関数の書式は次の通りです。

type(object)

引数に指定してオブジェクトのデータ型を取得します。

type("Hello")
--> <class 'str'>
type(123)
--> <class 'int'>

type 関数で取得した型オブジェクトは is 演算子を使用することで指定したデータ型と同じかどうかを調べることができます。

print(type("Hello") is str)
>> True
print(type("Hello") is int)
>> False
print(type(123) is int)
>> True
print(type(123.4) is int)
>> False

複数のデータ型と比較する場合には in 演算子を使用することで調べることができます。

print(type("Hello") in (str, int))
>> True
print(type(123) in (str, int))
>> True
print(type(123.4) in (str, int))
>> False

このように type 関数を使用することで、引数に指定したオブジェクトのデータ型を取得したり、指定したデータ型と同じかどうかを判定することができます。

サンプルコード

次のサンプルを見てください。

print(type("str"))
>> <class 'str'>
print(type(100))
>> <class 'int'>
print(type(14.5))
>> <class 'float'>
print(type(7.0 + 5j))
>> <class 'complex'>
print(type([1, 2, 3]))
>> <class 'list'>
print(type((1, 2, 3)))
>> <class 'tuple'>
print(type({1:"A", 2:"B", 3:"C"}))
>> <class 'dict'>
print(type(True))
>> <class 'bool'>
print(type(None))
>> <class 'NoneType'>

Python で使用される主なデータ型について type 関数でどのような値が帰ってくるのかを確認しました。

-- --

もう一つサンプルを見てください。

mylist = [2, "ab", 3.5, True, 4]
total = 0

for val in mylist:
    if type(val) in (int, float):
        print("val:" + str(val))
        total += val

>> val:2
>> val:3.5
>> val:4

print("total:" + str(total))
>> total:9.5

リストに格納された値のデータ型を調べ、整数型または浮動小数点数型だった場合は値を出力して合計を計算しました。

-- --

Python の組み込み関数の一つである type 関数の使い方について解説しました。

( Written by Tatsuo Ikura )

Profile
profile_img

著者 / TATSUO IKURA

プログラミングや開発環境構築の解説サイトを運営しています。