可變長度的參數傳遞
def p(fmt, *arg): print fmt % arg # 傳多個參數 s1 = "hello" s2 = "world" p("%s %s", s1, s2) # 把 list 的 element 當作參數 l = ["Allen", "Billy", "Elmer"] p("%s %s %s", *tuple(l)) # 混合模式 l = ["Allen", "Billy", "Elmer"] s = "hello" p("%s, %s %s %s", *((s, ) + tuple(l)))Output:
hello world Allen Billy Elmer hello, Allen Billy Elmer
Wrapper function 的寫法
def func(name, tel, city=None): print "name=%s" % name print "tel=%d" % tel print "city=%s" % city def wrapper(*args, **kwargs): print args print kw func(*args, **kwargs) wrapper("benson", 3345, city="Taipei")Output:
('benson', 3345) {'city': 'Taipei'} name=benson tel=3345 city=Taipei由此可見,arg 是 tuple,kwargs 是 dict 型態
這邊沒寫好可能會出現 error
only named arguments may follow *expression
*args 與 args 的差別
def func(x, y, z): print x+y+z def wrapper1(*args): # with star func(*args) def wrapper2(args): # without star func(*args) wrapper1(1, 2, 3) wrapper2([1, 2, 3])Output:
6 6
參考資料
Python, tuple arguments playing nicely with others - Stack Overflow
沒有留言:
張貼留言