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!