LoginSignup
23
19

More than 5 years have passed since last update.

困ったときのpartial

Last updated at Posted at 2016-12-07

Pythonの隠れ便利モジュール、functools

特にfunctools.partial関数めちゃくちゃ使います。

一部の引数を固定した関数を返す、といえばいいのか説明が難しいんですが。

sample.py
from functools import partial


def sayhello(message=u"hello", to=u"ryo"):
    print(u"{1}さん、{0}".format(message, to))


def main():
    sayhello()

    konnnichiwa = partial(sayhello, u"こんにちわ")

    konnnichiwa("nishizawa")
    konnnichiwa("takahashi")


if __name__ == "__main__":
    main()

を実行すると

> python sample.py
ryoさん、hello
nishizawaさん、こんにちわ
takahashiさん、こんにちわ

となります。

PySideのコールバック関数などをやっつけるときに活躍します

23
19
0

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
23
19