อาร์กิวเมนต์แบบอิสระ

Python ระดับกลางสำหรับนักพัฒนา

Jasmin Ludolf

Curriculum Manager

ข้อจำกัดของอาร์กิวเมนต์แบบกำหนด

def average(values):
    """Find the mean in a sequence of values and round to two decimal places."""

    average_value = sum(values) / len(values)
    rounded_average = round(average_value, 2)
    return rounded_average

# Using six arguments print(average(15, 29, 4, 13, 11, 8))
TypeError: average() takes 1 positional argument but 6 were given
Python ระดับกลางสำหรับนักพัฒนา

อาร์กิวเมนต์เชิงตำแหน่งแบบอิสระ

  • Docstring ช่วยอธิบายวิธีใช้ฟังก์ชันที่กำหนดเอง

  • อาร์กิวเมนต์แบบอิสระช่วยให้ฟังก์ชันรับอาร์กิวเมนต์ได้ไม่จำกัดจำนวน

# Allow any number of positional, non-keyword arguments
def average(*args):
    # Function code remains the same
  • ชื่อตามธรรมเนียม: *args

  • ใช้ได้หลากหลายรูปแบบและให้ผลลัพธ์ที่ถูกต้อง!

Python ระดับกลางสำหรับนักพัฒนา

การใช้อาร์กิวเมนต์เชิงตำแหน่งแบบอิสระ

# Calling average with six positional arguments
print(average(15, 29, 4, 13, 11, 8))
13.33
Python ระดับกลางสำหรับนักพัฒนา

Args รวมเป็น iterable เดียว

  • *: แปลงอาร์กิวเมนต์ให้เป็น iterable เดียว (tuple)
# Calculating across multiple lists
print(average(*[15, 29], *[4, 13], *[11, 8]))
13.33
Python ระดับกลางสำหรับนักพัฒนา

อาร์กิวเมนต์คีย์เวิร์ดแบบอิสระ

# Use arbitrary keyword arguments
def average(**kwargs):

average_value = sum(kwargs.values()) / len(kwargs.values()) rounded_average = round(average_value, 2) return rounded_average
  • อาร์กิวเมนต์คีย์เวิร์ดแบบอิสระ: **kwargs

  • keyword=value

Python ระดับกลางสำหรับนักพัฒนา

การใช้อาร์กิวเมนต์คีย์เวิร์ดแบบอิสระ

# Calling average with six kwargs
print(average(a=15, b=29, c=4, d=13, e=11, f=8))
13.33
# Calling average with one kwarg
print(average(**{"a":15, "b":29, "c":4, "d":13, "e":11, "f":8}))
13.33
  • คู่ key-value แต่ละคู่ในดิกชันนารีจะถูกแมปกับอาร์กิวเมนต์คีย์เวิร์ดและค่าที่สอดคล้องกัน!
Python ระดับกลางสำหรับนักพัฒนา

Kwargs รวมเป็น iterable เดียว

# Calling average with three kwargs
print(average(**{"a":15, "b":29}, **{"c":4, "d":13}, **{"e":11, "f":8}))
13.33
Python ระดับกลางสำหรับนักพัฒนา

มาฝึกกันเถอะ!

Python ระดับกลางสำหรับนักพัฒนา

Preparing Video For Download...