python (1) 函數 參數

(素材來源:Python Cookbook中文版,美David Beazley & Brian K. Jones著,陳舸 譯)

 

一、接受任意數量參數的函數

以*打頭的參數只能作爲最後一個位置參數出現,以**打頭的參數只能作爲最後一個參數出現。

def anyargs(*args, **kwargs):

    print(args)  # tuple

    print(kwargs) # dict

1. 位置參數

使用*表示

In [5]: def avg(first, *rest): 
   ...:     print(type(rest)) 
   ...:     print(rest) 
   ...:     return (first + sum(rest))/(1 + len(rest)) 
   ...:                                                                                                            

In [6]: avg(1, 2, 3, 4)                                                                                            
<class 'tuple'>
(2, 3, 4)
Out[6]: 2.5

In [7]:  

2. 關鍵字參數 **

def make_element(name, value, **attrs):
    print(type(attrs))
    print(attrs)
    keyvals = [' %s="%s"' % item for item in attrs.items()]
    print('attrs.keys():', attrs.keys())
    print('attrs.values():', attrs.values())
    print('attrs.items():', attrs.items())
    print('keyvals:', keyvals)
    attr_str = ''.join(keyvals)
    print('attr_str:', attr_str)
    element = '<{name}{attrs}>{value}</{name}'.format(
    name=name,
    attrs=attr_str,
    value=html.escape(value))
    print('element:', element)
    print('html.escape:', html.escape(value))
    return element

# test
make_element('item', 'Albatross', size='large', quantity=6)
# =>out
<class 'dict'>
{'size': 'large', 'quantity': 6}
attrs.keys(): dict_keys(['size', 'quantity'])
attrs.values(): dict_values(['large', 6])
attrs.items(): dict_items([('size', 'large'), ('quantity', 6)])
keyvals: [' size="large"', ' quantity="6"']
attr_str:  size="large" quantity="6"
element: <item size="large" quantity="6">Albatross</item
html.escape: Albatross

# test
make_element('p', '<spam>')
# =>out
<class 'dict'>
{}
attrs.keys(): dict_keys([])
attrs.values(): dict_values([])
attrs.items(): dict_items([])
keyvals: []
attr_str: 
element: <p>&lt;spam&gt;</p
html.escape: &lt;spam&gt;

 

二、只接受關鍵字參數的函數

keyword-only參數,常常是一種提高代碼可讀性的好方法。

recv(1024, False)與recv(1024, block=False)對比。

放在以*打頭的參數或者一個單獨的*之後

1. 放在單獨的*之後

def recv(maxsize, *, block):
    'Receives a message'
    print('maxsize:', maxsize)
    print('block:', block)
    pass

# test
recv(1024, True)
# ==> out
TypeError: recv() takes 1 positional argument but 2 were given

# test2
recv(1024, block=True)

# ==>out2
maxsize: 1024
block: True

2. 放在*打頭的參數之後

def minimum(*values, clip=None):
    print('type(values):', type(values))
    print('values:', values)
    print('type(clip):', type(clip))
    print('clip:', clip)
    m = min(values)
    print('m:', m)
    if clip is not None:
        m = clip if clip > m else m
        print('m:', m)
    pass

# test1
minimum(1, 5, 2, -5, 10)
# ==>out1
type(values): <class 'tuple'>
values: (1, 5, 2, -5, 10)
type(clip): <class 'NoneType'>
clip: None
m: -5
# test2
minimum(1, 5, 2, -5, 10, clip=0)
# ==> out2
type(values): <class 'tuple'>
values: (1, 5, 2, -5, 10)
type(clip): <class 'int'>
clip: 0
m: -5
m: 0

 

三、顯示幫助信息

在函數中寫入''中,或使用註解。使用help(函數名)打印

def hello():
    'hello func help test'
    pass

# test
help(hello)

# ==> out
Help on function hello in module __main__:

hello()
    hello func help test

# fun2

def add(x:int, y:int) -> int:
    
    return x + y
# test2
help(add)
# ==>out2
Help on function add in module __main__:

add(x:int, y:int) -> int

 

四、元數據信息附加到函數參數上

函數的參數註解可以提示該函數應該如何使用。豐富文檔內容。

註解會出現在文檔中,使用help()可查看。

python解釋器不會附加語法意義到參數註解上。既不是類型檢查,也不會改變python的行爲。一些第三方工具和框架可能會爲註解加上語法含義。

任何類型的對象均可作爲註解,通常只有類和字符串最有意義。

註解只保留在__annotations__屬性中。

python沒有類型聲明,使用註解,可以帶來更多提示。def s(int a, int b): => SyntaxError: invalid syntax

def add(x:int, y:int) -> int:
    
    return x + y

# test1
help(add)
# ==>out1
Help on function add in module __main__:

add(x:int, y:int) -> int

# test2
add(1, 2)
#==> out2
3

# test3
add('1', '2')
# ==>out3
'12'

# test4
add.__annotations__
# ==>out4
{'x': int, 'y': int, 'return': int}

 

五、函數返回多個值——元組

元組通過逗號","來組成,不是圓括號(), 結果賦給多個變量,屬於元組解包,賦給一個變量,該變量即爲該元組

In [7]: a = (1, 2)                                                                                                                                                                                                                         

In [8]: a                                                                                                                                                                                                                                  
Out[8]: (1, 2)

In [9]: b = 1, 2                                                                                                                                                                                                                           

In [10]: b                                                                                                                                                                                                                                 
Out[10]: (1, 2)

In [11]: def myfun(): 
    ...:     return 1, 2, 3 
    ...:                                                                                                                                                                                                                                   

In [12]: a, b, c = myfun()                                                                                                                                                                                                                 

In [13]: a                                                                                                                                                                                                                                 
Out[13]: 1

In [14]: b                                                                                                                                                                                                                                 
Out[14]: 2

In [15]: c                                                                                                                                                                                                                                 
Out[15]: 3

In [16]:  




 

六、帶有默認參數的函數

 

 

 

 

 

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