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

פונקציות חלקיות


אתה יכול ליצור פונקציות חלקיות בפייתון על ידי השימוש בפונקציה החלקית מתוך הספרייה 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) נקרא. אין הבדל בדוגמה זו, אבל יש דוגמה בהמשך שבה זה משנה.

תרגיל

ערוך את הפונקציה המסופקת על ידי קריאת 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