Get started learning Python with DataCamp's free Intro to Python tutorial. Learn Data Science by completing interactive coding challenges and watching videos by expert instructors. Start Now!
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join 11 million other learners and get started learning Python for data science today!
Good news! You can save 25% off your Datacamp annual subscription with the code LEARNPYTHON23ALE25 - Click here to redeem your discount
部分関数
Pythonで部分関数を作成するには、functoolsライブラリのpartial関数を使用します。
部分関数を使用すると、x個のパラメーターを持つ関数から、パラメーターが少なく、値が固定された関数を派生させることができます。
必要なインポート:
from functools import partial
このコードは8を返します。
from functools import partial
def multiply(x, y):
return x * y
# 2で掛け算する新しい関数を作成
dbl = partial(multiply, 2)
print(dbl(4))
重要な注意点: デフォルト値は左から変数を置き換え始めます。この例では2がxに置き換わります。dbl(4)が呼び出されたとき、yは4になります。この例では違いはありませんが、以下の例では違いがあります。
Exercise
func()の最初の3つの変数をpartial()を使用して置き換えることで、指定された関数を編集してください。その後、新しい部分関数を使って、出力が60になるように1つの入力変数だけで印刷してください。
#Following is the exercise, function provided:
from functools import partial
def func(u, v, w, x):
return u*4 + v*3 + w*2 + x
#Enter your code here to create and print with your partial function
from functools import partial
def func(u, v, w, x):
return u*4 + v*3 + w*2 + x
p = partial(func,5,6,7)
print(p(8))
#test_object('p')
test_output_contains('60')
success_msg('Good job!')
This site is generously supported by DataCamp. DataCamp offers online interactive Python Tutorials for Data Science. Join over a million other learners and get started learning Python for data science today!