*args & **kwargs in Python

by 02:05 0 comments
Python မွာ arguments  ေတြယူဖို ့Function ေရးတဲ့အခါက်ရင္အသံုးျပဳႏိုင္တဲ့ Special Symbols ၂ခုရွိပါတယ္။
၁ခုကေတာ့ *args ပါ။ ေနာက္တစ္ခုကေတာ့ **kwargs ေပါ့။ ကြ်န္ေတာ္ကိုယ္တိုင္လဲဘာမွန္းမသိပဲတိုင္ပတ္ဘူးေသးတယ္။ Python Documentation ျပန္လွန္လိုက္ေနာက္ဆံုး Google ပါ၀င္ကူရေတာ့တာပါပဲ။
ဒီ၂ခုကိုတစ္ခုခ်င္းစီရွင္းျပပါမယ္

*args

*args ဆိုတာကေတာ့ fucntion တစ္ခုမွာသင္သတ္မွတ္ခဲ့တဲ့ arguments အေရအတြက္ထက္ပိုယူႏိုင္ေအာင္လုပ္ေပးႏိုင္ပါတယ္။ (including zero extra arguments.) ပိုရွင္းေအာင္ code ေလးနဲ ့တြဲရွင္းျပပါမယ္။
 def func_with_two(one, two):  
   """  
   This function only takes in two arguments because we explicitly  
   defined two formal parameters. Any more or any less will cause an  
   error.  
   """  
   
 def func_with_start_args(*args):  
   """  
   This function can take in any number of arguments, including zero!  
   """  
   
 def func_with_both(one, two, *args):  
   This function requires <i>at least</i> two arguments. The *args at the end  
   says that it can take just two arguments or any number of arguments as long  
   as there are at least two.  
   """  
def func_with_two(one, two):
အေပၚဆံုးပာာကေတာ့ကြ်န္ေတာ္တို ့ေရးေနၾကေပါ့ ဒီမွာေတာ့ argument ၂ခုပါမယ္။ argument က ၂ခုထက္ပိုေပးလို ့ပဲျဖစ္ျဖစ္ ၂ခုထက္နည္းေနရင္ပဲျဖစ္ျဖစ္အလုပ္လုပ္မွာမပာုတ္ပါဘူး။

def func_with_start_args(*args):
သူကေတာ့ *args ကိုထည့္အသံုးျပဳထားေတာ့ arguments ေတြကိုၾကိုက္သလိုေပးျပီးအသံုးျပဳႏိုင္ပါတယ္။

def func_with_both(one, two, *args):
ဒါက်ေတာ့အေပၚက၂ခုကိုေပါင္းလိုက္တယ္ေပါ့ေလ။ အဲ့လိုေရးလိုက္ရင္ေျပာခ်င္တာက arguments ေတြကို အနည္းဆံုး ၂ခုနဲ ့၂ခုထက္ပိုေပးႏိုင္တယ္လို ့ဆိုလိုတာပါ။ ေသခ်ာတာကေတာ့ ၂ခုေတာ့အနည္းဆံုးေပးကိုေပးရမွာပါ။

ဒါေတြကတကယ္တန္းလဲလိုအပ္တဲ့ေနရာေတြမွာအသံုးျပဳၾကပါတယ္။ ဥပမာေလးတစ္ခုျပေပးထားပါမယ္။

ဥပမာေလးကေတာ့ arguments ေတြကိုၾကိဳက္သေလာက္ထည့္ပါမယ္ ျပီးရင္ထည့္လိုက္တဲ့ arguments ေတြကို multiply လုပ္ပါမယ္။
 >>> from operator import mul  
 >>> from functools import reduce  
 >>>  
 >>> def multiply(*args):  
 .......    return reduce(mul, args)  
 .......  
 >>> multiply(3, 5, 1, 5)  
 75  
 >>>  

mul နဲ ့ reduce ကိုေတာ့သိမယ္ထင္ပါတယ္။ မသိလဲ Python Documentation ၾကီးလွန္ဖတ္ေပါ့ေလ။
ဒါဆို **kwargs ဆိုတာကေကာဘာလဲ?

**kwargs

** ကေတာ့ key arguments ေတြကို pass လုပ္ေပးႏိုင္ပါတယ္။ Function ထဲကို variable pass လုပ္တဲ့အခါက်ရင္ key argument ပဲထည့္ေပးတာမ်ိဳးပါ။ ေအာက္က code ေလးကိုဖတ္ၾကည့္ရင္သေဘာေပါက္မွာပါ။
 >>> def print_table(**kwargs):  
 .......    for key, value in kwargs.items():  
 .......      print(key, value)  
 .......  
 >>> print_table(a = 1, b = 2, c = 3)  
 ('a', 1)  
 ('c', 3)  
 ('b', 2)  
သူက Dictionary လိုပါပဲ။ print ျပန္ထုတ္တဲ့အခါက order ေတာ့မျဖစ္ဘူးေပါ့ေလ။
ဒီေလာက္ဆို *args နဲ ့ **kwargs ကိုသေဘာေပါက္မယ္ထင္ပါတယ္။
PyLab (c) 2016

Pylab

Developer

Keep calm and love Python

0 comments:

Post a Comment