hx0011yy 发表于 2017-4-28 08:15:52

python核心编程学习(六)

  一个函数传参数的例子:
  '''Created on 2012-3-8@author: Administrator'''#!/usr/bin/env pythondef testit(func,*nkwargs,**kwargs):try:retval = func(*nkwargs,**kwargs)result = (True,retval)except Exception,diag:result = (False,str(diag))return resultdef test():funcs = (int,long,float)vals=(1234,12.34,'1234','12.34')for eachFunc in funcs:print '-'*20for eachVal in vals:retval = testit(eachFunc,eachVal)if retval:print '%s(%s)=' % (eachFunc.__name__,eachVal), retvalelse:print '%s(%s)=FAILED:' % (eachFunc.__name__,eachVal), retvalif __name__=='__main__':test()   
运行结果如下:
  --------------------int(1234)= 1234int(12.34)= 12int(1234)= 1234int(12.34)=FAILED: invalid literal for int() with base 10: '12.34'--------------------long(1234)= 1234long(12.34)= 12long(1234)= 1234long(12.34)=FAILED: invalid literal for long() with base 10: '12.34'--------------------float(1234)= 1234.0float(12.34)= 12.34float(1234)= 1234.0float(12.34)= 12.34
注意如下:
  retval = testit(eachFunc,eachVal)每次循环传递int,long,float 三个工厂的函数,retval = func(*nkwargs,**kwargs)每次接收一个数字,默认这个数字赋值的形参为nkwargs。
页: [1]
查看完整版本: python核心编程学习(六)