Python में *args और **kwargs
In this page:
def function_name(*args, **kwargs):
# args is a tuple, kwargs is a dict
function_name(value1, value2, key=value)
*args क्या है?
*args किसी function को उसके named parameters से आगे कितने भी positional arguments लेने देता है, उन्हें function के अंदर एक tuple में collect कर देता है -- यह तब उपयोगी है जब आपको पहले से पता न हो कि caller कितनी values pass करेगा।
उदाहरण: What is *args?
def total(*args): # collects any number of positional args into a tuple
print(args)
return sum(args)
print(total(1, 2, 3))
**kwargs क्या है?
**kwargs keyword arguments के लिए वही काम करता है, किसी भी extra arguments को एक dictionary में collect कर देता है जो parameter names को values से map करती है -- यह आमतौर पर हर option को अलग से list किए बिना arbitrary options को किसी दूसरे function तक forward करने के लिए इस्तेमाल होता है।
उदाहरण: What is **kwargs?
def show(**kwargs): # collects any keyword args into a dict
print(kwargs)
show(name="Alex", age=30)
Standard Parameters को *args के साथ Mix करना
आप एक ही function में *args से पहले साधारण named parameters define कर सकते हैं; उन named parameters के consume करने के बाद बचे किसी भी positional arguments अपने-आप *args tuple में overflow हो जाते हैं।
उदाहरण: Mixing Standard Parameters with *args
def greet(greeting, *names): # names collects everything after greeting
for name in names:
print(greeting, name)
greet("Hi", "Alex", "Sam")
*args और **kwargs को Mix करना
दोनों को एक definition में combine करते समय, Python एक सख़्त क्रम चाहता है: पहले standard parameters, फिर *args, फिर **kwargs -- यह क्रम भाषा द्वारा ही enforce किया जाता है, सिर्फ़ style की convention नहीं है।
उदाहरण: Mixing *args and **kwargs
def info(id, *args, **kwargs): # order matters: named param, then *args, then **kwargs
print(id, args, kwargs)
info(1, "extra", city="NYC")
* और ** से Unpacking
* और ** operators call site पर उल्टे तरीके से भी काम करते हैं: *a_list किसी list के items को अलग-अलग positional arguments में unpack कर देता है, और **a_dict किसी dictionary के items को call के लिए keyword arguments में unpack कर देता है।
उदाहरण: Unpacking with * and **
def add(a, b, c):
return a + b + c
values = [1, 2, 3]
print(add(*values)) # * unpacks the list into three positional arguments
data = {"a": 1, "b": 2, "c": 3}
print(add(**data)) # ** unpacks the dict into keyword arguments
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: