Pythonにはさまざまなデータ型があり、それらは「標準型階層(Standard Type Hierarchy)」として整理されています。本記事では、Pythonのデータモデルについて 初心者向けにハンズオン形式 で解説していきます!
「コードを書きながら理解したい!」という方は、ぜひPythonを実際に動かしながら試してみてください💡
🔹 Pythonの標準型階層とは?
Pythonのデータ型はすべて object
クラス を基底(親)としており、そこから派生しています。
例えば、int
(整数型)、str
(文字列型)、list
(リスト型)などがこの標準型階層の一部です。
Pythonの標準型の例
型 | 説明 |
---|---|
int |
整数 (42 ) |
float |
浮動小数点数 (3.14 ) |
complex |
複素数 (3 + 4j ) |
str |
文字列 ("hello" ) |
list |
リスト ([1, 2, 3] ) |
tuple |
タプル ((1, 2, 3) ) |
dict |
辞書 ({"name": "Alice"} ) |
set |
集合 ({1, 2, 3} ) |
bool |
真偽値 (True , False ) |
NoneType |
None |
では、実際にコードを書いて確認していきましょう!✨
🛠 ハンズオン – Pythonのデータ型を確認しよう!
1️⃣ すべての型は object
から派生している
Pythonのすべての型は object
を基底クラスとして持っています。まず、object
の親クラスを確認してみましょう。
print(object.__base__) # すべての型の親クラスを確認
👉 出力: None
これは object
がPythonの 最上位の型 であることを意味します。
次に、int
や str
の親クラスを確認してみましょう。
print(int.__base__) # int の親クラス
print(str.__base__) # str の親クラス
👉 どちらも object
になっている ことが確認できます!
2️⃣ 数値型(Numeric Types)
Pythonには、数値を表す型がいくつかあります。
print(type(42)) # int (整数)
print(type(3.14)) # float (浮動小数点数)
print(type(3 + 4j)) # complex (複素数)
👉 int
、float
、complex
の3種類 があることがわかります。
💡 ハンズオン: isinstance
を使って、変数が特定の型かどうかをチェックしてみましょう。
print(isinstance(42, int)) # True
print(isinstance(3.14, float)) # True
print(isinstance(3 + 4j, complex)) # True
3️⃣ シーケンス型(Sequence Types)
リストやタプル、文字列などは 「シーケンス型」 に分類されます。
print(type([1, 2, 3])) # list
print(type((1, 2, 3))) # tuple
print(type("hello")) # str
💡 ハンズオン: これらの型が collections.abc.Sequence
に属しているか確認してみましょう。
from collections.abc import Sequence
print(isinstance([1, 2, 3], Sequence)) # True
print(isinstance((1, 2, 3), Sequence)) # True
print(isinstance("hello", Sequence)) # True
👉 リスト、タプル、文字列はすべて「シーケンス型」 であることがわかります!
4️⃣ マップ型(辞書型 – Mapping Types)
辞書 (dict
) は キーと値のペアを持つデータ型 です。
my_dict = {"name": "Alice", "age": 25}
print(type(my_dict)) # dict
💡 ハンズオン: collections.abc.Mapping
に属しているかチェック!
from collections.abc import Mapping
print(isinstance(my_dict, Mapping)) # True
👉 dict
は 「マップ型」 に分類されます。
5️⃣ 集合型(Set Types)
集合 (set
) は 重複しない要素のコレクション です。
my_set = {1, 2, 3, 4}
print(type(my_set)) # set
💡 ハンズオン: collections.abc.Set
に属しているか確認してみましょう。
from collections.abc import Set
print(isinstance(my_set, Set)) # True
👉 set
は 「集合型」 であることが確認できます。
6️⃣ その他の型
Pythonには、ほかにもいくつかの特殊な型があります。
型 | 説明 |
---|---|
bool |
真偽値 (True , False ) |
NoneType |
None (値がないことを示す) |
bytes |
バイト列(バイナリデータ) |
range |
範囲オブジェクト (range(10) ) |
💡 ハンズオン: NoneType
の型を確認してみよう。
print(type(None)) # NoneType
👉 NoneType
は None
を表す特別な型です。
🎯 まとめ
✅ Pythonのデータ型はすべて object
から派生している!
✅ 数値型には int
、float
、complex
がある!
✅ シーケンス型には list
、tuple
、str
がある!
✅ dict
はマップ型、set
は集合型!
✅ bool
、NoneType
、bytes
などの特殊な型もある!
Pythonのデータモデルを理解すると、 「このデータがどの型なのか?」 を正しく把握でき、コードの可読性やバグ防止に役立ちます!🎉
さあ、Pythonのデータ型をもっと深く学んで、スムーズなコーディングを目指しましょう!🐍💻