python核心编程 第十一章 函数

#encoding=utf-8
from time import ctime,sleep
#内嵌函数,闭包
#tsfunc()是一个装饰器,显示何时调用函数的时间戳,定义了内部函数wrappedFunc(),
#装饰器返回值是一个包装了的函数

def tsfunc(func):
    def wrappedFunc():
        print '[%s] %s() called ' % (ctime(),func.__name__)
        return func()
    return wrappedFunc

#装饰器
@tsfunc
def foo():
    pass

foo()
sleep(4)

for i in range(2):
    sleep(1)
    foo()

 

'''---------------------传递参数--------------------------'''
#python的函数不同于c,函数就像对象,是可以被引用的,也可以作为参数传入函数
#也可以作为列表或字典等容器对象的元素
#函数区分与其他对象,函数是可调用的

#可以用其他对象作为函数的别名
def foo():
    print 'in foo()'

bar = foo    #bar,foo引用到了同一个函数对象
bar()

#函数作为参数传入其他函数.来进行调用
def bar(argFunc):
    argFunc()
bar(foo)

#传递和调用(内建)函数
def covert(func,seq):
    'conv sequence of numbers to same type'
    return [func(eachNum) for eachNum in seq]
    #列表解析

myseq = (123,45.67,-6.2E8,999999999L)
print covert(int,myseq)
print covert(long,myseq)
print covert(float,myseq)

 

'''-------------形式参数---------------'''
#位置参数,没有默认参数,传入函数参数个数,必须和声明一致

def foo(who):
    print 'hello',who
#foo() #foo()takes exactly 1 argument (0 given)
#foo('hi','world')  foo()takes exactly 1 argument (0 given)
foo('world')

#默认参数,参数名=默认值
def taxMe(cost,rate=0.0825):
    print cost+(cost * rate)
taxMe(100)
taxMe(100,0.05)
#必需的参数在默认参数之前
#non-default argument follows deault argument
# def taxMe2(rate=0.6,cost):
#     return cost*rate

#可以不按参数的顺序给出参数
def net_conn(host,port):
    print host,port
net_conn('kappa',8000)
net_conn(port=8080,host='chino')

 

'''------------非关键字可变长参数(元组)*-------------------------'''
#使用*指定元组作为参数,**指定字典的元素
#所有形式参数必须先于非正式的参数

def tuple(arg1,arg2='B',*theRest):
    print 'formal arg1:',arg1
    print 'formal arg2:',arg2
    for eacharg in theRest:
        print 'another arg:',eacharg
tuple('abc')
tuple(23,4)
tuple(23,'abc','xyz',456)

 


'''----------关键字可变参数(字典)**--------------------------'''
#关键字参数变量应该是函数定义的最后一个参数

def dict(arg1,arg2='B',**theRest):
    print 'formal arg1:',arg1
    print 'formal arg2:',arg2
    for eacharg in theRest.keys():
        print 'another arg %s:%s'%(eacharg,str(theRest[eacharg]))
dict(1220,740.0,c='grail')
dict(arg2='tales',c=123,d='poe',arg1='mystery')
dict('one',d=10,e='zoo',men=('freud','gaudi'))
#还可以混用,字典要放最后
def newfoo(arg1,arg2,*nkw,**kw):
    print 'formal arg1:',arg1
    print 'formal arg2:',arg2
    for eacharg in nkw:
        print 'other non-keyword arg:',eacharg
    for eacharg in kw.keys():
        print 'another keyword arg %s:%s'%(eacharg,str(kw[eacharg]))
newfoo('wolf','3','projects',freud=90,gamble=96)

 

posted @ 2016-08-15 17:09  zdmlcmepl  阅读(201)  评论(0编辑  收藏  举报