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
Partielle Funktionen
Sie können in Python partielle Funktionen erstellen, indem Sie die Funktion partial
aus der Bibliothek functools
verwenden.
Partielle Funktionen ermöglichen es, aus einer Funktion mit x Parametern eine Funktion mit weniger Parametern abzuleiten, wobei feste Werte für die begrenzte Funktion festgelegt werden.
Erforderlicher Import:
from functools import partial
Dieser Code wird 8 zurückgeben.
from functools import partial
def multiply(x, y):
return x * y
# create a new function that multiplies by 2
dbl = partial(multiply, 2)
print(dbl(4))
Ein wichtiger Hinweis: Die Standardwerte werden beginnen, die Variablen von links zu ersetzen. Die 2 wird x ersetzen. y wird 4 entsprechen, wenn dbl(4) aufgerufen wird. In diesem Beispiel macht es keinen Unterschied, aber im folgenden Beispiel tut es das.
Übung
Bearbeiten Sie die bereitgestellte Funktion, indem Sie partial() aufrufen und die ersten drei Variablen in func() ersetzen. Dann drucken Sie mit der neuen partiellen Funktion, indem Sie nur eine Eingabevariable verwenden, sodass die Ausgabe 60 ergibt.
#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!