type() 型/動的クラス作成
最終更新:2026-09-22
type() 型/動的クラス作成
type(obj) はオブジェクトの型を返します;type(name, bases, dict) は新しいクラスを動的に作成します。
| カテゴリ | 組み込み関数 |
|---|---|
| 種類 | 組み込み関数 |
| Python バージョン | all |
📝 構文
type(object)
type(name, bases, dict)
⚙️ 引数
| object 必須 | One-arg form: the object whose type is queried. |
|---|---|
| name 必須 | Three-arg form: the class name (string); mutually exclusive with the one-arg form. |
| bases 必須 | Three-arg form: a tuple of base classes. |
| dict 必須 | Three-arg form: the class namespace dict (attributes/methods). |
戻り値:One-arg form: the object's type. Three-arg form: a newly created class.
💥 例外
TypeError— Raised when name is not a string in the three-arg form.
▶ 例
下のコードを編集し「実行」をクリックすると、出力パネルに結果が表示されます:
実行結果:
int
10
🏷️ 関連する組み込み関数
💡 関連するケース
さらに多くのケースは近日公開予定です。
❓ よくある質問
Qtype(42) は何を返しますか?
A を返します。引数1つの形式はオブジェクトの型を返します。
Qtype(x) == int と isinstance(x, int) の違いは?
Aisinstance はサブクラスも認識します。bool は int のサブクラスなので、isinstance(True, int) は True ですが type(True) == int は False です。一般には isinstance の方が安全です。
Qtype(name, bases, dict) の3引数形式は何のため?
A新しいクラスを動的に作成します。type('MyClass', (object,), {'x': 10}) は class MyClass(object): x = 10 と等価です。これはメタクラスプログラミングの基礎です。
Qオブジェクトの型名を取得するには?
Atype(obj).__name__ を使います。例:type(42).__name__ は 'int' を返します。print(type(x)) は 形式を表示します。