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
Partialfunksjoner
Du kan lage delvise funksjoner i Python ved å bruke del-funksjonen fra functools-biblioteket.
Delvise funksjoner lar en avlede en funksjon med x parametere til en funksjon med færre parametere og faste verdier satt for den mer begrensede funksjonen.
Importer det som trengs:
from functools import partial
Denne koden vil returnere 8.
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))
En viktig merknad: standardverdiene vil begynne å erstatte variabler fra venstre. 2 erstatter x. y vil være lik 4 når dbl(4) kalles. Det gjør ingen forskjell i dette eksemplet, men det gjør det i eksemplet nedenfor.
Exercise
Rediger funksjonen ved å kalle partial() og erstatte de første tre variablene i func(). Deretter skriver du ut med den nye delvise funksjonen ved å bruke bare én inputvariabel slik at utdataene tilsvarer 60.
#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!