Python函数使用汇总

# -*- coding: utf8 -*-

#不带参数函数
def fun():
    print('hello world')

fun() #hello world

#----------------------------------------
#带参数函数
def fun1(x, y):
    print('x+y=%d' % (x+y))
    return x+y

fun1(1, 3) #x+y=4
#----------------------------------------
#默认参数(默认参数自后的参数必须全部带默认参数,同C语言)
def fun2(x, y = 'a'):
    print('x=%d, y=%s' % (x,y))


fun2(2) #x=2, y=a
#----------------------------------------
#当调用引用关联参数名时,顺序可以不固定
def fun3(x, y, z):
    print('x=%s, y=%s, z=%s' % (x,y,z))


fun3(y = 'b', z = 'c', x = 'a') #x=a, y=b, z=c  传入顺序加上参数名称后可以改变
#----------------------------------------
#不定长参数,*x参数实际上相当于传进去了一个元组
def fun4(*x):
    print(x)
    for i in x:
        print('x=%s' % i)

fun4(1,2,3,4,5)
#(1, 2, 3, 4, 5)
#x=1
#x=2
#x=3
#x=4
#x=5

#----------------------------------------
#3.0版本之前,不定长参数只能有一个且放在最后 如果def fun5(x, *y, z):就会报错.3.0之后版本支持,\但是调用时最后一个参数需要具体指明z等于多少z = value
def fun5(x, *y):
    for i in y:
        x += i
    return x

sum = fun5(2, 1, 2, 3, 4, 5)
print(sum) #17

#----------------------------------------
#内嵌函数,外部无法调用
def fun6(x):
    def fun0(y):
        return y**2
    print(fun0(x+1))

fun6(2) #9

#----------------------------------------
#闭包1(构成条件:1,改函数返回内部函数的调用; 2,内部函数用到了外部函数作用域中的变量(如x))
def fun7(x):
    def fun7_1(y):
        return x*y
    return fun7_1

f = fun7(8)
f1 = fun7(10)
x = f(5)
y = f1(5)
print(x)  #40
print(y)  #50

#闭包2()
'''
#3.0之前的版本有缺陷,只能通过下面的函数实现方式实现,3.0之后的版本可以加nonlocal关键字声明x为fun8_1的外部变量,类似于global
def fun8():
    x = 10
    def fun8_1():
        nonlocal x #3.0以后的版本这样声明一下,系统就知道x为fun8_1的外部变量了
        x *= x  #x试图被修改,由于x属于fun8_1函数的外部变量, 而在fun8_1中的x系统会视为fun8_1的内部变量,就会找不到,导致报错
        return x
    return fun8_1()
'''
def fun8():
    x = [10] #列表在下方使用的时候不会被屏蔽
    def fun8_1():
        x[0] *= x[0]  #x试图被修改,由于x属于fun8_1函数的外部变量, 而在fun8_1中的x系统会视为fun8_1的内部变量,就会找不到,导致报错
        return x[0]
    return fun8_1()

z = fun8()
print(z) #100

#----------------------------------------
#匿名函数lambda 参数...:返回值
fun9 = lambda x,y,z: x+y*z

print(fun9(1,2,3))  #7

#----------------------------------------
#重要函数filter(条件函数, 列表), 在列表中筛选出满足条件为True的内容并组成对象返回,该对象可以转化成列表
listT = list(filter(lambda x: x%2, range(10)))
print(listT)  #[1, 3, 5, 7, 9]

#重要函数map(条件函数, 列表), 将列表中的元素一一处理并组成对象返回,该对象可以转化成列表
listT = list(map(lambda x: x+2, range(10)))
print(listT)  #[2, 3, 4, 5, 6, 7, 8, 9, 10, 11]

#----------------------------------------
#函数文档(使用help会打印的更好)
def fun10():
    '此处添加函数文档,用来描述函数的参数信息,功能等'

def fun11():
    '''
    这样可以添加多行
    利用fun.__doc__或者help(fun)可以显示函数文档
    '''

fun10.__doc__
#此处添加函数文档,用来描述函数的参数信息,功能等


fun11.__doc__
#这样可以添加多行\n利用fun.__doc__或者help(fun)可以显示函数文档\n


help(fun10)
#Help on function fun in module __main__:
#
#fun10()
#    此处添加函数文档,用来描述函数的参数信息,功能等

help(fun11)
#Help on function fun in module __main__:
#
#fun11()
#    这样可以添加多行
#    利用fun.__doc__或者help(fun)可以显示函数文档


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章