Python type() 関数

Python 内置函数Python 組み込み関数


説明

type() 関数は、最初のパラメータのみを指定した場合はオブジェクトの型を返し、3つのパラメータを指定した場合は新しい型オブジェクトを返します。

isinstance() と type() の違い:

  • type() はサブクラスを親クラスの型とは見なさず、継承関係を考慮しません。

  • isinstance() はサブクラスを親クラスの型と見なし、継承関係を考慮します。

2つの型が同じかどうかを判断する場合は、isinstance() の使用を推奨します。

構文

以下は type() メソッドの構文です:

type(object)
type(name, bases, dict)

パラメータ

  • name -- クラスの名前。
  • bases -- 基底クラスのタプル。
  • dict -- ディクショナリ、クラス内で定義された名前空間の変数。

戻り値

1つのパラメータの場合はオブジェクトの型を返し、3つのパラメータの場合は新しい型オブジェクトを返します。


例

以下に type 関数を使用した例を示します:

# 1つのパラメータの例 >>> type(1) <type 'int'> >>> type('サンプル') <type 'str'> >>> type([2]) <type 'list'> >>> type({0:'zero'}) <type 'dict'> >>> x = 1 >>> type( x ) == int # 型が等しいかどうかを判断 True # 3つのパラメータ >>> class X(object): ... a = 1 ... >>> X = type('X', (object,), dict(a=1)) # 新しい型 X を生成 >>> X <class '__main__.X'>

type() と isinstance() の違い:

class A: pass class B(A): pass isinstance(A(), A) # returns True type(A()) == A # returns True isinstance(B(), A) # returns True type(B()) == A # returns False

Python 内置函数Python 組み込み関数

その他の拡張機能