一. 变长参数函数
变长参数的函数,是指参数个数可变、参数类型不定的函数。
Python中允许两种类型的函数变长参数
1. 元祖(Tuple)变长参数: 适用于位置参数的数量不固定,但在函数中使用这些参数时候,无需知道这些参数的名字的场合。在函数定义中,元祖变长参数用星号‘*’表示
def show_message(message,*tupleName):
for name in tupleName:
print message,",",name
if __name__ == '__main__':
show_message("Good Morning","Jack","Evans","Rosa Hasa",893,"Zion")
运行结果:
Good Morning , Jack
Good Morning , Evans
Good Morning , Rosa Hasa
Good Morning , 893
Good Morning , Zion
2. 字典(Dictionary)变长参数: 适用于位置参数的数量不固定,但在函数中使用这些参数时候,需要知道这些参数的名字的场合。在函数定义中,字典变长参数用双星号‘**’表示
from django.template.defaultfilters import title
def check_book(**dictParm):
if dictParm.has_key('Price'):
price = int (dictParm['Price'])
if price > 100:
print "******I want to buy this book!******"
print "The book information are as follows:"
for key in dictParm.keys():
print key,":",dictParm[key]
print ""
if __name__ == "__main__":
check_book(author="James", Title='Economics Introduction')
check_book(author="Linda",Title="Deppin in Python",Date="2015-5-1",Price=302)
check_book(Date="2002-3-19",Title="Cooking book",Price =20)
运行结果:
The book information are as follows:
Title : Economics Introduction
author : James
******I want to buy this book!******
The book information are as follows:
Date : 2015-5-1
Price : 302
Title : Deppin in Python
author : Linda
The book information are as follows:
Date : 2002-3-19
Price : 20
Title : Cooking book
二. 匿名函数
匿名函数是指易雷,无需定义标识符(函数名)的函数或者子程序,一般用于代码中存在一次函数引用的场合。
Python用lambda语法定义匿名函数
#example for Lambda function in python
import datetime
from test.pickletester import __main__
def nameFunc(a):
return "I'm named function with param %s" %a
def call_func(func,param):
print datetime.datetime.now()
print func(param)
print ""
if __name__ == "__main__":
call_func(nameFunc, 'hello')
call_func(lambda x: x*2,9)
call_func(lambda y: y*y,-4)
运行结果
2019-07-05 20:50:54.237000
I'm named function with param hello
2019-07-05 20:50:54.237000
18
2019-07-05 20:50:54.237000
16