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

Μερικές συναρτήσεις


You can create partial functions in python by using the partial function from the functools library.

Οι μερικές συναρτήσεις επιτρέπουν σε κάποιον να παραγάγει μια συνάρτηση με x παραμέτρους σε μια συνάρτηση με λιγότερες παραμέτρους και με καθορισμένες τιμές για τη περιορισμένη συνάρτηση.

Απαιτείται εισαγωγή:

python from functools import partial

Αυτός ο κώδικας θα επιστρέψει 8.

```python 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). Δεν κάνει διαφορά σε αυτό το παράδειγμα, αλλά κάνει στο παρακάτω παράδειγμα.

Άσκηση

Επεξεργαστείτε τη συνάρτηση που παρέχεται καλώντας το 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