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, використовуючи функцію partial із бібліотеки functools.

Часткові функції дозволяють створити функцію з x параметрами, призначену для обмеженої кількості параметрів, зі встановленими фіксованими значеннями для більш обмеженої функції.

Необхідний імпорт:

from functools import partial

Цей код поверне 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))

Важлива примітка: значення за замовчуванням будуть починати замінювати змінні зліва. Це 2 замінить x. y дорівнюватиме 4, коли викликається dbl(4). Це не змінює у цьому прикладі, але змінює в прикладі нижче.

Exercise

Відредагуйте надану функцію, викликавши partial() і замінивши перші три змінні у func(). Потім надрукуйте з новою частковою функцією, використовуючи лише одну вхідну змінну, так щоб вихідний результат дорівнював 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!

Previous Tutorial Next Tutorial Take the Test
Copyright © learnpython.org. Read our Terms of Use and Privacy Policy