python核心程式設計學習(六)

2021-09-01 04:04:51 字數 1136 閱讀 9245

乙個函式傳引數的例子:

''' created on 2012-3-8 @author: administrator ''' #!/usr/bin/env python def testit(func,*nkwargs,**kwargs): try: retval = func(*nkwargs,**kwargs) result = (true,retval) except exception,diag: result = (false,str(diag)) return result def test(): funcs = (int,long,float) vals=(1234,12.34,'1234','12.34') for eachfunc in funcs: print '-'*20 for eachval in vals: retval = testit(eachfunc,eachval) if retval[0]: print '%s(%s)=' % (eachfunc.__name__,eachval), retval[1] else: print '%s(%s)=failed:' % (eachfunc.__name__,eachval), retval[1] if __name__=='__main__': test()

執行結果如下:

-------------------- int(1234)= 1234 int(12.34)= 12 int(1234)= 1234 int(12.34)=failed: invalid literal for int() with base 10: '12.34' -------------------- long(1234)= 1234 long(12.34)= 12 long(1234)= 1234 long(12.34)=failed: invalid literal for long() with base 10: '12.34' -------------------- float(1234)= 1234.0 float(12.34)= 12.34 float(1234)= 1234.0 float(12.34)= 12.34

注意如下:

retval = testit(eachfunc,eachval)每次迴圈傳遞int,long,float 三個工廠的函式,retval = func(*nkwargs,**kwargs)每次接收乙個數字,預設這個數字賦值的形參為nkwargs。

python核心程式設計學習(一)

以下是核心程式設計中乙個stack的例子 created on 2012 3 6 author administrator usr bin env python stack def pu def popit if len stack 0 print has empty else print remo...

python核心程式設計學習(三)

核心程式設計中的檔案操作的例子 created on 2012 3 7 author administrator usr bin env python import os for tmpdir in c r if os.path.isdir tmpdir print tmpdir break els...

python核心程式設計學習(四)

乙個計算簡單加減法的例子 created on 2012 3 7 author administrator usr bin env python from operator import add,sub from random import randint,choice ops maxtries 2...