【Python】callable 関数の使い方と実行結果

Python

Python の組み込み関数 callableコーラブル の使い方です。

callable 関数で、objectオブジェクト が『関数として呼び出し可能であるかいなか』を判定します。

そのコード例と、実行結果を載せました。

あと、『エラーになったコード例』も書きました。

(Python) callable(object) の説明によると、

  • callable(object) が True なら、関数として呼び出し可能(True でも呼び出しが失敗する可能性もある)。
  • callable(object) が False なら、関数としては、決して呼び出せない。

とのことでした。

callable 関数の用途です。

自分は、『オブジェクトにドット . を付けてアクセスできる属性ぞくせい (attributeアトリビュート)』の中から、『関数のようなもの(括弧かっこを付けて呼び出せるもの)を列挙れっきょしたい』といったときに、よく使用しました。

エラーになったコード例

callable 関数で、エラーになったコードれいです。

引数ひきすう無しで呼び出したら、エラーになりました。

(Python) callable(object)

callable() # 引数無し
TypeError: callable() takes exactly one argument (0 given)

False なら関数として呼び出せない

callable 関数に渡したときに False になる『オブジェクト』や『属性』についてです。

それらを関数として呼び出そうとしたら(カッコを付けて呼び出そうとしたら)、『callable ではありません』というむねのエラーになりました。

complex オブジェクトの場合です。

(Python) class complex([real[, imag]])

x = complex(3, 4)
callable(x) # (3+4j)
False
x = complex(3, 4)
x() # (3+4j)
TypeError: 'complex' object is not callable

complex オブジェクトの real 属性の場合です。

(Python) class numbers.Real

x = complex(3, 4)
callable(x.real) # 3.0
False
x = complex(3, 4)
x.real() # 3.0
TypeError: 'float' object is not callable

function

callable 関数に、functionファンクション(関数)とその属性ぞくせいを渡した結果です。

(Python) callable(object)

(Python) ラムダ (lambda)

(Python) 関数定義

(Python) フォーマット済み文字列リテラル (f-string, f''

(Python) instance.__class__

(Python) definition.__name__

(Python) repr(object)

callable(lambda x:x) # <function <lambda> at 0x0000000000000000>
True
callable((lambda x:x).__class__) # <class 'function'>
True
callable((lambda x:x).__name__) # '<lambda>'
False
callable((lambda x:x).__class__.__name__) # 'function'
False
def jisaku(x):
    """自作関数です。"""
    return x

print(f'{callable(jisaku)} # jisaku {repr(jisaku)}')
print(f'{callable(jisaku.__doc__)} # jisaku.__doc__ {repr(jisaku.__doc__)}')
print(f'{callable(jisaku.__class__)} # jisaku.__class__ {repr(jisaku.__class__)}')
print(f'{callable(jisaku.__name__)} # jisaku.__name__ {repr(jisaku.__name__)}')
print(f'{callable(jisaku.__class__.__name__)} # jisaku.__class__.__name__ {repr(jisaku.__class__.__name__)}')
True # jisaku <function jisaku at 0x0000000000000000>
False # jisaku.__doc__ '自作関数です。'
True # jisaku.__class__ <class 'function'>
False # jisaku.__name__ 'jisaku'
False # jisaku.__class__.__name__ 'function'

組み込み定数

callable 関数に、組み込み定数とその属性ぞくせいを渡した結果です。

(Python) callable(object)

(Python) 組み込み定数

(Python) int.to_bytes(length, byteorder, *, signed=False)

(Python) instance.__class__

(Python) definition.__name__

callable(False) # False
False
callable(True) # True
False
callable((True).to_bytes) # <built-in method to_bytes of bool object at 0x0000000000000000>
True
callable(None) # None
False
callable((None).__class__) # <class 'NoneType'>
True
callable((None).__class__.__name__) # 'NoneType'
False

int

callable 関数に、intイント整数せいすう)とその属性ぞくせいを渡した結果です。

(Python) callable(object)

(Python) class int([x])

(Python) int.to_bytes(length, byteorder, *, signed=False)

(Python) class numbers.Real

(Python) フォーマット済み文字列リテラル (f-string, f''

int クラスの場合です。

callable(int) # <class 'int'>
True
callable(int.to_bytes) # <method 'to_bytes' of 'int' objects>
True
callable(int.real) # <attribute 'real' of 'int' objects>
False

整数リテラルの場合です。

(Python) 整数リテラル (Integer literals)

callable(255) # 255
False
callable((255).to_bytes) # <built-in method to_bytes of int object at 0x0000000000000000>
True
callable((255).real) # 255
False

int 型の数値を変数に入れた場合です。

x = 255
print(f'{callable(x)} # {x}')
False # 255
x = 255
print(f'{callable(x.to_bytes)} # {x.to_bytes}')
True # <built-in method to_bytes of int object at 0x0000000000000000>
x = 255
print(f'{callable(x.real)} # {x.real}')
False # 255

str

callable 関数に、strエスティーアール(文字列)とその属性ぞくせいを渡した結果です。

(Python) callable(object)

(Python) class str(object='')

(Python) str.lower()

(Python) フォーマット済み文字列リテラル (f-string, f''

str クラスの場合です。

callable(str) # <class 'str'>
True
callable(str.lower) # <method 'lower' of 'str' objects>
True

文字列リテラルの場合です。

(Python) 文字列およびバイト列リテラル

callable('ABC') # 'ABC'
False
callable('ABC'.lower) # <built-in method lower of str object at 0x0000000000000000>
True

文字列を変数に入れた場合です。

x = 'ABC'
print(f'{callable(x)} # {x}')
False # ABC
x = 'ABC'
print(f'{callable(x.lower)} # {x.lower}')
True # <built-in method lower of str object at 0x0000000000000000>

bytes

callable 関数に、bytesバイツ とその属性ぞくせいを渡した結果です。

(Python) callable(object)

(Python) class bytes([source[, encoding[, errors]]])

(Python) bytes.replace(old, new[, count])

(Python) フォーマット済み文字列リテラル (f-string, f''

bytes クラスの場合です。

callable(bytes) # <class 'bytes'>
True
callable(bytes.replace) # <method 'replace' of 'bytes' objects>
True

バイト列リテラルの場合です。

(Python) 文字列およびバイト列リテラル

callable(b'\x00\x01\x02') # b'\x00\x01\x02'
False
callable(b'\x00\x01\x02'.replace) # <built-in method replace of bytes object at 0x0000000000000000>
True

バイト列を変数に入れた場合です。

x = b'\x00\x01\x02'
print(f'{callable(x)} # {x}')
False # b'\x00\x01\x02'
x = b'\x00\x01\x02'
print(f'{callable(x.replace)} # {x.replace}')
True # <built-in method replace of bytes object at 0x0000000000000000>

list

callable 関数に、listリスト とその属性ぞくせいを渡した結果です。

(Python) callable(object)

(Python) class list([iterable])

(Python) ミュータブルなシーケンス型

(Python) フォーマット済み文字列リテラル (f-string, f''

list クラスの場合です。

callable(list) # <class 'list'>
True
callable(list.copy) # <method 'copy' of 'list' objects>
True

角括弧かくかっこで書いたリストの場合です。

(Python) class list([iterable])

callable([0, 1, 2]) # [0, 1, 2]
False
callable([0, 1, 2].copy) # <built-in method copy of list object at 0x0000000000000000>
True

リストを変数に入れた場合です。

x = [0, 1, 2]
print(f'{callable(x)} # {x}')
False # [0, 1, 2]
x = [0, 1, 2]
print(f'{callable(x.copy)} # {x.copy}')
True # <built-in method copy of list object at 0x0000000000000000>

datetime

callable 関数に、datetimeデートタイム(日時)やその属性ぞくせいを渡した結果です。

dirディーアイアール 関数で『属性名ぞくせいめい』を列挙れっきょして、getattrゲットアトリビュート 関数で『属性』を取得して、それを callable 関数に渡してみました。

(Python) callable(object)

(Python) class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

(Python) dir([object])

(Python) getattr(object, name[, default])

(Python) フォーマット済み文字列リテラル (f-string, f''

(Python) class type(object)

import datetime
# datetime.datetime のインスタンスを作ります。
x = datetime.datetime(2020, 12, 31, 23, 58, 59)
# callabe 関数で判定します。
print(f'{callable(x)} # x {type(x)}')

# 属性の名前を列挙します。
for name in dir(x):
    # 属性を取得します。
    x_attr = getattr(x, name)
    # callabe 関数で判定します。
    print(f'{callable(x_attr)} # x.{name} {type(x_attr)}')
False # x <class 'datetime.datetime'>
True # x.__add__ <class 'method-wrapper'>
True # x.__class__ <class 'type'>
True # x.__delattr__ <class 'method-wrapper'>
True # x.__dir__ <class 'builtin_function_or_method'>
False # x.__doc__ <class 'str'>
True # x.__eq__ <class 'method-wrapper'>
True # x.__format__ <class 'builtin_function_or_method'>
True # x.__ge__ <class 'method-wrapper'>
True # x.__getattribute__ <class 'method-wrapper'>
True # x.__gt__ <class 'method-wrapper'>
True # x.__hash__ <class 'method-wrapper'>
True # x.__init__ <class 'method-wrapper'>
True # x.__init_subclass__ <class 'builtin_function_or_method'>
True # x.__le__ <class 'method-wrapper'>
True # x.__lt__ <class 'method-wrapper'>
True # x.__ne__ <class 'method-wrapper'>
True # x.__new__ <class 'builtin_function_or_method'>
True # x.__radd__ <class 'method-wrapper'>
True # x.__reduce__ <class 'builtin_function_or_method'>
True # x.__reduce_ex__ <class 'builtin_function_or_method'>
True # x.__repr__ <class 'method-wrapper'>
True # x.__rsub__ <class 'method-wrapper'>
True # x.__setattr__ <class 'method-wrapper'>
True # x.__sizeof__ <class 'builtin_function_or_method'>
True # x.__str__ <class 'method-wrapper'>
True # x.__sub__ <class 'method-wrapper'>
True # x.__subclasshook__ <class 'builtin_function_or_method'>
True # x.astimezone <class 'builtin_function_or_method'>
True # x.combine <class 'builtin_function_or_method'>
True # x.ctime <class 'builtin_function_or_method'>
True # x.date <class 'builtin_function_or_method'>
False # x.day <class 'int'>
True # x.dst <class 'builtin_function_or_method'>
False # x.fold <class 'int'>
True # x.fromisocalendar <class 'builtin_function_or_method'>
True # x.fromisoformat <class 'builtin_function_or_method'>
True # x.fromordinal <class 'builtin_function_or_method'>
True # x.fromtimestamp <class 'builtin_function_or_method'>
False # x.hour <class 'int'>
True # x.isocalendar <class 'builtin_function_or_method'>
True # x.isoformat <class 'builtin_function_or_method'>
True # x.isoweekday <class 'builtin_function_or_method'>
False # x.max <class 'datetime.datetime'>
False # x.microsecond <class 'int'>
False # x.min <class 'datetime.datetime'>
False # x.minute <class 'int'>
False # x.month <class 'int'>
True # x.now <class 'builtin_function_or_method'>
True # x.replace <class 'builtin_function_or_method'>
False # x.resolution <class 'datetime.timedelta'>
False # x.second <class 'int'>
True # x.strftime <class 'builtin_function_or_method'>
True # x.strptime <class 'builtin_function_or_method'>
True # x.time <class 'builtin_function_or_method'>
True # x.timestamp <class 'builtin_function_or_method'>
True # x.timetuple <class 'builtin_function_or_method'>
True # x.timetz <class 'builtin_function_or_method'>
True # x.today <class 'builtin_function_or_method'>
True # x.toordinal <class 'builtin_function_or_method'>
False # x.tzinfo <class 'NoneType'>
True # x.tzname <class 'builtin_function_or_method'>
True # x.utcfromtimestamp <class 'builtin_function_or_method'>
True # x.utcnow <class 'builtin_function_or_method'>
True # x.utcoffset <class 'builtin_function_or_method'>
True # x.utctimetuple <class 'builtin_function_or_method'>
True # x.weekday <class 'builtin_function_or_method'>
False # x.year <class 'int'>

以上です。

スポンサーリンク
シェアする(押すとSNS投稿用の『編集ページ』に移動します)
フォローする(RSSフィードに移動します)
スポンサーリンク
シラベルノート
タイトルとURLをコピーしました