અને ફંક્શનને દલીલો સ્વીકાર કરવા દે છે. વધારાની દલીલોને tuple માં એકત્રિત કરે છે; વધારાની દલીલોને dict માં એકત્રિત કરે છે. (નામો સંમેલન છે — અને જે મહત્વપૂર્ણ છે.)
અને ફંક્શનને દલીલો સ્વીકાર કરવા દે છે. વધારાની દલીલોને tuple માં એકત્રિત કરે છે; વધારાની દલીલોને dict માં એકત્રિત કરે છે. (નામો સંમેલન છે — અને જે મહત્વપૂર્ણ છે.)
*args**kwargs*args**kwargs***def total(*args): # collects all positional args into a tuple
print(args) # e.g. (1, 2, 3)
return sum(args)
total(1, 2, 3) # 6
total(1, 2, 3, 4, 5) # 15 — any number of args
def configure(**kwargs): # collects keyword args into a dict
print(kwargs) # e.g. {"host": "localhost", "port": 8080}
for key, value in kwargs.items():
print(f"{key} = {value}")
configure(host="localhost", port=8080, debug=True)
def func(a, b, *args, **kwargs):
# a, b → required positional
# args → extra positional (tuple)
# kwargs → extra keyword (dict)
...
func(1, 2, 3, 4, x=5, y=6)
# a=1, b=2, args=(3, 4), kwargs={"x": 5, "y": 6}
જરૂરી ક્રમ છે: નિયમિત પરિમાણો, પછી *args, પછી **kwargs.
# `*` and `**` also UNPACK collections INTO arguments at the call site
numbers = [1, 2, 3]
total(*numbers) # same as total(1, 2, 3)
settings = {"host": "x", "port": 80}
configure(**settings) # same as configure(host="x", port=80)
સમાન વાક્યરચના list/dict ને વસ્તુ/કીવર્ડ દલીલોમાં અનપ્યાક કરે છે — દલીલો આગળ ધપાવવા માટે હાથી.
def wrapper(*args, **kwargs):
# accept ANY arguments and pass them through unchanged
return original_func(*args, **kwargs)
યો પસાર-થ્રુ પેટર્ન છે કે કેવી રીતે સજ્જાદીશ અને રૅપર ફંક્શન કોઈ પણ ફંક્શન હસ્તાક્ષર હેન્ડલ કરે છે.
*args/**kwargs લવચક ફંક્શન હસ્તાક્ષર સક્ષમ કરે છે જે કોઈ પણ સંખ્યા દલીલો સ્વીકાર કરે છે — સર્વોચ્ચ-હેતુ સાધનસામગ્રી, રૅપર અને ખાસ કરીને સજ્જાદીશ લખવા માટે જરૂરી (જે અજ્ઞાત હસ્તાક્ષર ફંક્શન *args, **kwargs દ્વારા રૅપ કરવા આવશ્યક છે).
અનપ્યાકિંગ દિશા (*list, **dict) દલીલો આગળ ધપાવવા કે ફેલાવવા માટે સમાન ઉપયોગી છે.
બંને એકત્રીકરણ અને અનપ્યાકિંગ સમજવું પુનઃઉપયોગી, સામાન્ય Python કોડ લખવા માટે અને આ વૈશિષ્ટ્યો પર આધાર રાખતી ઘણી લાયબ્રેરી APIs અને સજ્જાદીશ વાંચવા માટે ચાવી છે.