LoginSignup
8

More than 5 years have passed since last update.

Python独習に役立つ組み込み関数

Last updated at Posted at 2017-10-22

REPL環境でPythonの挙動を調べることは理解をよく助けてくれます。ここに便利なコマンドをまとめます。

コマンド一覧

python3
>>> id()
>>> type()
>>> dir()
>>> bool()
>>> help()

実用例と解説

id()

id()はオブジェクトの「識別値」を返すものです。
見た目が同じでもpythonは違うと認識していたり、逆のこともあります。
基本的に同じ数字は同じ識別値、同じ短い文字列は同じ識別値となります。
リストの識別値を調べてみると、興味深いでしょう。

>>> id(1)
1814648560
>>> id("a")
3024896
>>> a = [1,2]
>>> b = [1,2]
>>> id(a)
4500000648
>>> id(b)
4499932168

type()

type()はオブジェクトのクラスを調べます。

>>> type(1)
<class 'int'>
>>> type("1")
<class 'str'>

dir()

dir()は名前空間を調べます。クラスを渡すとそのクラスの名前空間を返します。

>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', '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']

bool()

真偽値を調べます。ifに渡すとどうなるかな、と迷ったときに便利です。

>>> bool()
False
>>> bool("")
False
>>> bool("any string")
True

help()

クラスや関数のヘルプを参照します。

>>> help(dir)
Help on built-in function dir in module builtins:

dir(...)
    dir([object]) -> list of strings

    If called without an argument, return the names in the current scope.
    Else, return an alphabetized list of names comprising (some of) the attributes
    of the given object, and of attributes reachable from it.
    If the object supplies a method named __dir__, it will be used; otherwise
    the default dir() logic is used and returns:
      for a module object: the module's attributes.
      for a class object:  its attributes, and recursively the attributes
        of its bases.
      for any other object: its attributes, its class's attributes, and
        recursively the attributes of its class's base classes.

>>> help(''.split)
Help on built-in function split:

split(...) method of builtins.str instance
    S.split(sep=None, maxsplit=-1) -> list of strings

    Return a list of the words in S, using sep as the
    delimiter string.  If maxsplit is given, at most maxsplit
    splits are done. If sep is not specified or is None, any
    whitespace string is a separator and empty strings are
    removed from the result.

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8