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)可以顯示函數文檔


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