לדלג לתוכן

3.2 פרמטרים לפונקציות הרצאה

ערך דיפולטי לפרמטרים

  • בפייתון אפשר להגדיר ערך דיפולטי לפרמטרים של פונקציות
    def send_message(message, author="You"):
        print(f"{author}: {message}")
    
    send_message("Hello!")  # Valid
    send_mesasge("Hello!", "User")  # Valid
    
  • במקרה הזה אם נקרא ל- send_message מבלי להעביר שום ערך לפרמטר author לפרמטר יהיה ערך של "You"

קיוורד ארגומנט vs פוזישנל ארגומנט

  • הדרך שבה העברנו עד כו ארגומנטים לפונקציות, נקרא "ארגומנט תלוי מיקום" או באנגלית positional argument (פוזישנל ארגומנט)
    add(5, 3) # Passing postional arguments
    
  • כשאנחנו מעבירים המון positional arguments בקריאה לפונקציה, זה מתחיל להיות מאוד לא ברור מה כל ארגומנט עושה.
  • בשביל זה יש לנו "ארגומנט תלוי שם" או באנגלית keyword argument (קייורד ארגומנט)
    add(first_number=5, second_number=3) # Passing keyword arguments
    
  • שימוש בקייורד ארגומנט זה טוב בשביל כתיבת קוד קריא.

הגבלות קייורד ארגומנט ופוזישנל ארגומנט

  • שימוש ב/ ו - * כפרמטרים לפונקציה, מאפשר לנו להגביל את המשתמש באיזה ארגומנטים הוא יכול להעביר כפוזישנל ואיזה קיוורד.

תו /

  • בשימוש / כל פרמטר שבא לפני התו לא יכול להועבר כקייורד ארגומנט!
    # Here message can't be passed as keyword argument!
    def send_message(message, /, author):
        print(f"{author}: {message}")
    
    
    send_message("Hello", "Ben")
    send_message("Hello", author="Ben")
    send_message(message="Hello", author="Ben")  # Error!! invalid
    

תו *

בשימוש * כל פרמטר שבא אחרי חייב להועבר כקייורד ארגומנט!

# Here author must be passed as keyword argument!
def send_message(message, *, author):
    print(f"{author}: {message}")

send_message("Hello", "Ben")  # Error!! invalid
send_message("Hello", author="Ben")
send_message(message="Hello", author="Ben")  

שימוש ביחד * ו - /

  • דוגמה של שימוש בשניהם ביחד
    # Here author must be passed as keyword argument and message can't be keyword argument.
    def send_message(message, /, *, author):
        print(f"{author}: {message}")
    
    send_message("Hello", "Ben")  # Error!! invalid
    send_message("Hello", author="Ben")
    send_message(message="Hello", author="Ben")  # Error!! invalid
    
  • כאן author חייב להיות קייורד ארגומנט ו- message חייב להיות פוזישנל

פיצול פרמטרים

ביטוי מכוכב - starred expression

  • כאשר אנחנו מעבירים פרמטרים לפונקציות, כוכביות מאפשרות לנו להעביר כמה פרמטרים במקביל
    # Define a function that takes three arguments
    def greet(name, age, city):
        print(f"Hello, {name}! You are {age} years old and live in {city}.")
    
    # Create a list with values to be passed to the function
    person_info = ['Alice', 25, 'Wonderland']
    
    # Use the unpacking feature to pass the values to the function
    greet(*person_info)
    
    # Create a dictionary with values to be passed to the function
    person_info_dict = {'name': 'Alice', 'age': 25, 'city': 'Wonderland'}
    
    greet(**person_info_dict)
    
  • כוכבית אחת מאפשרת להעביר positional arguments
  • שני כוכביות מאפשרות לנו להעביר keyword arguments

ארגס וקוורגס - Args and Kwargs

ארגס - args
- כאשר אנחנו מגדירים פרמטרים לפונקציה, ניתן להגדיר פרמטר מיוחד שמקבל מספר לא מוגדר של positional arguments כאשר מגדירים אותו עם כוכבית, הפרמטר הזה נקרא בדרך כלל args

def print_args(*args):
    for arg in args:
        print(arg)

print_args(1, 2, "three", [4, 5])

קוורגס - kwargs
- כאשר אנחנו מגדירים פרמטרים לפונקציה, ניתן להגדיר פרמטר מיוחד שמקבל מספר לא מוגדר של keyword argument כאשר מגדירים אותו עם שני כוכביות, הפרמטר הזה נקרא בדרך כלל kwargs

def print_kwargs(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_kwargs(name="Alice", age=25, city="Wonderland")

  • שימוש בארגס וקוורגס ביחד:
    def print_args_and_kwargs(*args, **kwargs):
        for arg in args:
            print(arg)
    
        for key, value in kwargs.items():
            print(f"{key}: {value}")
    
    print_args_and_kwargs(1, 2, "three", name="Bob", age=30)
    
  • זה מאפשר לכתוב פונקציות שמקבלות אינסוף פרמטרים משני הסוגים בו זמנית.