溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么使用python函數(shù)參數(shù)高級(jí)

發(fā)布時(shí)間:2020-08-25 13:37:30 來源:億速云 閱讀:155 作者:Leah 欄目:編程語言

本篇文章給大家分享的是有關(guān)怎么使用python函數(shù)參數(shù)高級(jí),小編覺得挺實(shí)用的,因此分享給大家學(xué)習(xí),希望大家閱讀完這篇文章后可以有所收獲,話不多說,跟著小編一起來看看吧。

我們已經(jīng)了解了最基本的函數(shù),下面將要學(xué)習(xí)更多函數(shù)的特性。例如使用函數(shù)返回值,如何在不同的函數(shù)間傳遞不同的數(shù)據(jù)結(jié)構(gòu)等。

參數(shù)缺省值

我們初次介紹函數(shù)的時(shí)候,用的是下述例子:

def thank_you(name):
    # This function prints a two-line personalized thank you message.
    print("\nYou are doing good work, %s!" % name)
    print("Thank you very much for your efforts on this project.")
    
thank_you('Adriana')
thank_you('Billy')
thank_you('Caroline')

上述代碼中,函數(shù)都能正常工作。但是在不傳入?yún)?shù)時(shí),函數(shù)就會(huì)報(bào)錯(cuò)。如下所示:

def thank_you(name):
    # This function prints a two-line personalized thank you message.
    print("\nYou are doing good work, %s!" % name)
    print("Thank you very much for your efforts on this project.")
    
thank_you('Billy')
thank_you('Caroline')
thank_you()

出現(xiàn)這個(gè)錯(cuò)誤是合乎情理的。函數(shù)需要一個(gè)參數(shù)來完成它的工作,沒有這個(gè)參數(shù)就沒辦法工作。

這就引出了一個(gè)問題。有時(shí)候你想在不傳參數(shù)的時(shí)候讓函數(shù)執(zhí)行默認(rèn)的動(dòng)作。你可以通過設(shè)置參數(shù)的缺省值實(shí)現(xiàn)這個(gè)功能。缺省值是在函數(shù)定義的時(shí)候確定的。如下所示:

def thank_you(name='everyone'):
    # This function prints a two-line personalized thank you message.
    #  If no name is passed in, it prints a general thank you message
    #  to everyone.
    print("\nYou are doing good work, %s!" % name)
    print("Thank you very much for your efforts on this project.")
    
thank_you('Billy')
thank_you('Caroline')
thank_you()

在函數(shù)中有多個(gè)參數(shù),且其中一些參數(shù)的值基本不變時(shí),使用參數(shù)缺省值是非常有幫助的。它可以幫助函數(shù)調(diào)用者只關(guān)注他們關(guān)心的參數(shù)。

位置參數(shù)

使用函數(shù)的很重要的一點(diǎn)就是如何向函數(shù)中傳遞參數(shù)。我們已經(jīng)學(xué)到的都是最簡單的參數(shù)傳遞,只有一個(gè)參數(shù)。接下來我們了解一下如何傳遞兩個(gè)以上的參數(shù)。

我們創(chuàng)建一個(gè)包含 3 個(gè)參數(shù)的函數(shù),包含一個(gè)人的名,姓和年紀(jì)。如下所示:

def describe_person(first_name, last_name, age):
    # This function takes in a person's first and last name,
    #  and their age.
    # It then prints this information out in a simple format.
    print("First name: %s" % first_name.title())
    print("Last name: %s" % last_name.title())
    print("Age: %d\n" % age)

describe_person('brian', 'kernighan', 71)
describe_person('ken', 'thompson', 70)
describe_person('adele', 'goldberg', 68)

在這個(gè)函數(shù)中,參數(shù)是 first_name , last_name , age 。它們被稱為位置參數(shù)。Python 會(huì)根據(jù)參數(shù)的相對(duì)位置為它們賦值。在下面的調(diào)用語句中:

describe_person('brian', 'kernighan', 71)

我們給函數(shù)傳遞了 brian, kernighan, 71 三個(gè)值。Python 就會(huì)根據(jù)參數(shù)位置將 first_name 和 brian 匹配,last_name 和 kernighan 匹配,age 和 71 匹配。

這種參數(shù)傳遞方式是相當(dāng)直觀的,但是我們需要嚴(yán)格保證參數(shù)的相對(duì)位置。

如果我們混亂了參數(shù)的位置,就會(huì)得到一個(gè)無意義的結(jié)果或報(bào)錯(cuò)。如下所示:

def describe_person(first_name, last_name, age):
    # This function takes in a person's first and last name,
    #  and their age.
    # It then prints this information out in a simple format.
    print("First name: %s" % first_name.title())
    print("Last name: %s" % last_name.title())
    print("Age: %d\n" % age)

describe_person(71, 'brian', 'kernighan')
describe_person(70, 'ken', 'thompson')
describe_person(68, 'adele', 'goldberg')

這段代碼中,first_name 和 71 匹配,然后調(diào)用 first_name.title() ,而整數(shù)是無法調(diào)用 title() 方法的。

關(guān)鍵字參數(shù)

Python 中允許使用關(guān)鍵字參數(shù)。所謂關(guān)鍵字參數(shù)就是在調(diào)用函數(shù)時(shí),可以指定參數(shù)的名字給參數(shù)賦值。改寫上述代碼,示例如下:

def describe_person(first_name, last_name, age):
    # This function takes in a person's first and last name,
    #  and their age.
    # It then prints this information out in a simple format.
    print("First name: %s" % first_name.title())
    print("Last name: %s" % last_name.title())
    print("Age: %d\n" % age)

describe_person(age=71, first_name='brian', last_name='kernighan')
describe_person(age=70, first_name='ken', last_name='thompson')
describe_person(age=68, first_name='adele', last_name='goldberg')

這樣就能工作了。Python 不再根據(jù)位置為參數(shù)賦值。而是通過參數(shù)名字匹配對(duì)應(yīng)的參數(shù)值。這種寫法可讀性更高。

混合位置和關(guān)鍵字參數(shù)

有時(shí)候混合使用位置和關(guān)鍵字參數(shù)是有意義的。我們還是用上述例子,增添一個(gè)參數(shù)繼續(xù)使用位置參數(shù)。如下所示:

def describe_person(first_name, last_name, age, favorite_language):
    # This function takes in a person's first and last name,
    #  their age, and their favorite language.
    # It then prints this information out in a simple format.
    print("First name: %s" % first_name.title())
    print("Last name: %s" % last_name.title())
    print("Age: %d" % age)
    print("Favorite language: %s\n" % favorite_language)

describe_person('brian', 'kernighan', 71, 'C')
describe_person('ken', 'thompson', 70, 'Go')
describe_person('adele', 'goldberg', 68, 'Smalltalk')

我們假設(shè)每個(gè)人調(diào)用這個(gè)函數(shù)的時(shí)候都會(huì)提供 first_name 和 last_name。但可能不會(huì)提供其他信息。因此 first_name 和 last_name 使用位置參數(shù),其他參數(shù)采用關(guān)鍵字參數(shù)的形式。如下所示:

def describe_person(first_name, last_name, age=None, favorite_language=None, died=None):
    """ 
    This function takes in a person's first and last name, their age, 
    and their favorite language.
    It then prints this information out in a simple format.
    """
    
    print("First name: %s" % first_name.title())
    print("Last name: %s" % last_name.title())
    
    # Optional information:
    if age:
        print("Age: %d" % age)
    if favorite_language:
        print("Favorite language: %s" % favorite_language)
    if died:
        print("Died: %d" % died)
    # Blank line at end.
    print("\n")

接受任意數(shù)量的參數(shù)

利用關(guān)鍵字參數(shù)我們可以靈活處理各種調(diào)用語句。然而,我們還有其他一些問題需要處理。我們考慮一個(gè)函數(shù),接收兩個(gè)數(shù)字參數(shù),并打印數(shù)字之和。示例如下:

def adder(num_1, num_2):
    # This function adds two numbers together, and prints the sum.
    sum = num_1 + num_2
    print("The sum of your numbers is %d." % sum)
    
# Let's add some numbers.
adder(1, 2)
adder(-1, 2)
adder(1, -2)

這個(gè)函數(shù)運(yùn)行良好。但是如果我們傳入3個(gè)參數(shù)呢,看起來這種情況也應(yīng)該是可以作算術(shù)運(yùn)算的。如下所示:

def adder(num_1, num_2):
    # This function adds two numbers together, and prints the sum.
    sum = num_1 + num_2
    print("The sum of your numbers is %d." % sum)
    
# Let's add some numbers.
adder(1, 2, 3)

出乎意料,函數(shù)出錯(cuò)了。為什么呢?

這是因?yàn)闊o論采用什么形式的參數(shù),函數(shù)只接受2個(gè)參數(shù)。事實(shí)上在這種情況下,函數(shù)只能恰好接受2個(gè)參數(shù)。怎么樣才能解決參數(shù)個(gè)數(shù)問題呢?

接受任意長度的序列

Python 幫助我們解決了函數(shù)接受參數(shù)個(gè)數(shù)的問題。它提供了一種語法,可以讓函數(shù)接受任意數(shù)量的參數(shù)。如果我們在參數(shù)列表的最后一個(gè)參數(shù)前加一個(gè)星號(hào),這個(gè)參數(shù)就會(huì)收集調(diào)用語句的剩余參數(shù)并傳入一個(gè)元組。(剩余參數(shù)是指匹配過位置參數(shù)后剩余的參數(shù))示例如下:

def example_function(arg_1, arg_2, *arg_3):
    # Let's look at the argument values.
    print('\narg_1:', arg_1)
    print('arg_2:', arg_2)
    print('arg_3:', arg_3)
    
example_function(1, 2)
example_function(1, 2, 3)
example_function(1, 2, 3, 4)
example_function(1, 2, 3, 4, 5)

你也可以使用 for 循環(huán)來處理剩余參數(shù)。

def example_function(arg_1, arg_2, *arg_3):
    # Let's look at the argument values.
    print('\narg_1:', arg_1)
    print('arg_2:', arg_2)
    for value in arg_3:
        print('arg_3 value:', value)

example_function(1, 2)
example_function(1, 2, 3)
example_function(1, 2, 3, 4)
example_function(1, 2, 3, 4, 5)

我們現(xiàn)在就可以重寫 adder() 函數(shù),示例如下:

def adder(num_1, num_2, *nums):
    # This function adds the given numbers together,
    #  and prints the sum.
    
    # Start by adding the first two numbers, which
    #  will always be present.
    sum = num_1 + num_2
    
    # Then add any other numbers that were sent.
    for num in nums:
        sum = sum + num
        
    # Print the results.
    print("The sum of your numbers is %d." % sum)

    
# Let's add some numbers.
adder(1, 2)
adder(1, 2, 3)
adder(1, 2, 3, 4)

接受任意數(shù)量的關(guān)鍵字參數(shù)

Python 也提供了一種接受任意數(shù)量的關(guān)鍵字參數(shù)的語法。如下所示:

def example_function(arg_1, arg_2, **kwargs):
    # Let's look at the argument values.
    print('\narg_1:', arg_1)
    print('arg_2:', arg_2)
    print('arg_3:', kwargs)
    
example_function('a', 'b')
example_function('a', 'b', value_3='c')
example_function('a', 'b', value_3='c', value_4='d')
example_function('a', 'b', value_3='c', value_4='d', value_5='e')

上述代碼中,最后一個(gè)參數(shù)前有兩個(gè)星號(hào),代表著收集調(diào)用語句中剩余的所有鍵值對(duì)參數(shù)。這個(gè)參數(shù)常被命名為 kwargs 。這些參數(shù)鍵值對(duì)被存儲(chǔ)在一個(gè)字典中。我們可以循環(huán)字典取出參數(shù)值。如下所示:

def example_function(arg_1, arg_2, **kwargs):
    # Let's look at the argument values.
    print('\narg_1:', arg_1)
    print('arg_2:', arg_2)
    for key, value in kwargs.items():
        print('arg_3 value:', value)
    
example_function('a', 'b')
example_function('a', 'b', value_3='c')
example_function('a', 'b', value_3='c', value_4='d')
example_function('a', 'b', value_3='c', value_4='d', value_5='e')
def example_function(**kwargs):
    print(type(kwargs))
    for key, value in kwargs.items():
        print('{}:{}'.format(key, value))
        
example_function(first=1, second=2, third=3)
example_function(first=1, second=2, third=3, fourth=4)
example_function(name='Valerio', surname='Maggio')

此前我們創(chuàng)建過一個(gè)描述人的信息的函數(shù)。但是我們只能傳遞有限的信息,因?yàn)閰?shù)的個(gè)數(shù)在定義時(shí)已經(jīng)被限制?,F(xiàn)在利用剛剛學(xué)習(xí)的知識(shí),我們可以傳遞任意數(shù)量任意形式的信息,如下所示:

def describe_person(first_name, last_name, **kwargs):
    # This function takes in a person's first and last name,
    #  and then an arbitrary number of keyword arguments.
    
    # Required information:
    print("First name: %s" % first_name.title())
    print("Last name: %s" % last_name.title())
    
    # Optional information:
    for key in kwargs:
        print("%s: %s" % (key.title(), kwargs[key]))
    
    # Blank line at end.
    print("\n")

describe_person('brian', 'kernighan', favorite_language='C')
describe_person('ken', 'thompson', age=70)
describe_person('adele', 'goldberg', age=68, favorite_language='Smalltalk')
describe_person('dennis', 'ritchie', favorite_language='C', died=2011)
describe_person('guido', 'van rossum', favorite_language='Python')

以上就是怎么使用python函數(shù)參數(shù)高級(jí),小編相信有部分知識(shí)點(diǎn)可能是我們?nèi)粘9ぷ鲿?huì)見到或用到的。希望你能通過這篇文章學(xué)到更多知識(shí)。更多詳情敬請關(guān)注億速云行業(yè)資訊頻道。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI