オブジェクトや変数の型を確認する方法(関数オブジェクトの型名)

Python 2.7

Pythonで型を調べる方法は簡単で、isinstanceという組み込み関数を使用します。

listかどうかを調べる際は、

if isinstance([], list):
  print "this is list type."

if isinstance(1, int):
  print "this is integer type."

というふうにします。

listやintはオブジェクトであり、[]や1はそれぞれのオブジェクトのインスタンスです。

Pythonでは関数の引数は型を限定しない(全てオブジェクトなので)使い方ができるので、型を調べることで引数に応じて処理を分けるという仕組みが実現出来ます。

それでは、関数オブジェクトの型名は何でしょうか?また、クラスの型名は何でしょうか?それはtype関数を使用することで調べることができます。

Pythonでは全ての変数や関数はオブジェクトなので、引数として渡すことができるのですが、その際に渡った引数の型を調べて処理を分けるときには、型の種類を知らなくてはなりません。型が何かを調べる際にはtype関数を使用します。

type関数でいろんなオブジェクトの型を調べたサンプルを書きました。

#!/usr/bin/python
# -*- coding:utf-8 -*-

import os

class OwnClass():
    def __init__(self):
        self.param = 123
    
    def func(self):
        print self.param
        return True

if __name__ == '__main__':
    owc = OwnClass()

    print "string     's'              is '%s'" % (type("s"))
    print "integer    1                is '%s'" % (type(1))
    print "float      0.1              is '%s'" % (type(0.1))
    print "float      1.0e-3           is '%s'" % (type(1.0e-3))
    print "list       []               is '%s'" % (type([]))
    print "tuple      ()               is '%s'" % (type(()))
    print "None                        is '%s'" % (type(None))
    print "function   'int'            is '%s'" % (type(int))
    print "function   'type'           is '%s'" % (type(type))
    print "module     'os'             is '%s'" % (type(os))
    print "member     'os.path.sep'    is '%s'" % (type(os.path.sep))
    print "method     'os.path.exists' is '%s'" % (type(os.path.exists))
    print "my class   'owc'            is '%s'" % (type(owc))
    print "my member  'owc.param'      is '%s'" % (type(owc.param))
    print "my method  'owc.func'       is '%s'" % (type(owc.func))

出力は以下のようになります。

string     's'              is '<type 'str'>'
integer    1                is '<type 'int'>'
float      0.1              is '<type 'float'>'
float      1.0e-3           is '<type 'float'>'
list       []               is '<type 'list'>'
tuple      ()               is '<type 'tuple'>'
None                        is '<type 'NoneType'>'
function   'int'            is '<type 'type'>'
function   'type'           is '<type 'type'>'
module     'os'             is '<type 'module'>'
member     'os.path.sep'    is '<type 'str'>'
method     'os.path.exists' is '<type 'function'>'
my class   'owc'            is '<type 'instance'>'
my member  'owc.param'      is '<type 'int'>'
my method  'owc.func'       is '<type 'instancemethod'>'