Python dir() 関数
dir()Pythonでオブジェクトの属性とメソッドのリストを取得するための組み込み関数です。
dir()オブジェクトのすべての属性とメソッド名を含むリストを返します。この関数は、未知のオブジェクトを探索するとき、コードをデバッグするとき、クラスの構造を理解するときに非常に役立ちます。
単語の意味: dirであるdirectory(ディレクトリ)の略で、ここでは属性とメソッドのリストを指します。
基本構文とパラメータ
構文形式
dir(object) dir()
パラメータの説明
- パラメータ object(省略可能):
- 型: 任意のオブジェクト
- 説明: 属性リストを取得するオブジェクト。引数を渡さない場合、現在のスコープの名前リストを返します。
関数の説明
- 戻り値: 属性とメソッドの名前を含む文字列リストを返します。
- 特徴: リストはアルファベット順に並べ替えられます。
例
例1:オブジェクトの属性を表示
例
# リストのすべての属性とメソッドを表示
print(dir([]))
# 出力: ['__add__', '__class__', '__contains__', ... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# 文字列の属性を表示
print(dir(""))
# 出力: ['__add__', '__class__', '__contains__', ... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# 辞書の属性を表示
print(dir({}))
# 出力: ['__class__', '__contains__', ... 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
print(dir([]))
# 出力: ['__add__', '__class__', '__contains__', ... 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
# 文字列の属性を表示
print(dir(""))
# 出力: ['__add__', '__class__', '__contains__', ... 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
# 辞書の属性を表示
print(dir({}))
# 出力: ['__class__', '__contains__', ... 'clear', 'copy', 'get', 'items', 'keys', 'pop', 'popitem', 'setdefault', 'update', 'values']
実行結果の予想:
オブジェクトのすべての属性とメソッド名のリストを返します。
コードの解説:
- 二重アンダースコアで
__始まるものは、特別な属性/メソッド(マジックメソッド)です。 - 二重アンダースコアがないものは公開メソッドです。例えば
append,sortなど。
例1:オブジェクトの属性を表示
例
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
# インスタンスを作成
p = Person("Tom", 20)
# インスタンスの属性を表示
print(dir(p))
# 出力: ['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name']
# フィルタリングして特別なメソッド以外のみ表示
attrs = [attr for attr in dir(p) if not attr.startswith('_')]
print(attrs) # 出力: ['age', 'greet', 'name']
def __init__(self, name, age):
self.name = name
self.age = age
def greet(self):
return f"Hello, I'm {self.name}"
# インスタンスを作成
p = Person("Tom", 20)
# インスタンスの属性を表示
print(dir(p))
# 出力: ['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name']
# フィルタリングして特別なメソッド以外のみ表示
attrs = [attr for attr in dir(p) if not attr.startswith('_')]
print(attrs) # 出力: ['age', 'greet', 'name']
実行結果の予想:
['__class__', '__delattr__', '__dict__', '__init__', ... 'age', 'greet', 'name'] ['age', 'greet', 'name']
コードの解説:
__dict__オブジェクトのインスタンス属性が含まれます。- 二重アンダースコアで
__始まるメソッドを除外すると、公開属性を取得できます。
例3:引数なしで使用
例
# 引数なしで、現在のスコープの名前リストを返す
print(dir())
# 出力: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
# モジュールをインポートした後に確認
import os
print(dir())
# 'os' がリストに含まれる
# モジュールの属性を表示
import json
print(dir(json))
# 出力: ['JSONDecodeError', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'tool']
print(dir())
# 出力: ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
# モジュールをインポートした後に確認
import os
print(dir())
# 'os' がリストに含まれる
# モジュールの属性を表示
import json
print(dir(json))
# 出力: ['JSONDecodeError', '__all__', '__author__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'decoder', 'dump', 'dumps', 'encoder', 'load', 'loads', 'tool']
実行結果の予想:
現在のスコープで使用可能な名前のリストを返します。
dir()Pythonのオブジェクトとモジュールを探索するための強力なツールで、特にインタラクティブな学習やデバッグに適しています。
その他の拡張