溫馨提示×

溫馨提示×

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

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

Python中函數(shù)參數(shù)傳遞方法有哪些

發(fā)布時間:2023-04-13 11:03:17 來源:億速云 閱讀:123 作者:iii 欄目:編程語言

這篇文章主要介紹“Python中函數(shù)參數(shù)傳遞方法有哪些”的相關(guān)知識,小編通過實際案例向大家展示操作過程,操作方法簡單快捷,實用性強,希望這篇“Python中函數(shù)參數(shù)傳遞方法有哪些”文章能幫助大家解決問題。

定義和傳遞參數(shù)

parameters 和arguments 之間的區(qū)別是什么?

許多人交替使用這些術(shù)語,但它們是有區(qū)別的:

  • Parameters 是函數(shù)定義中定義的名稱

  • Arguments是傳遞給函數(shù)的值

Python中函數(shù)參數(shù)傳遞方法有哪些

紅色的是parameters , 綠色的是arguments。

傳遞參數(shù)的兩種方式

我們可以按位置和關(guān)鍵字傳遞參數(shù)。在下面的例子中,我們將值hello作為位置參數(shù)傳遞。值world 用關(guān)鍵字傳遞的。

 def the_func(greeting, thing):
 print(greeting + ' ' + thing)
 
 the_func('hello', thing='world')

位置參數(shù)和kwargs(關(guān)鍵字參數(shù))之間的區(qū)別在于傳遞位置參數(shù)的順序很重要。如果調(diào)用the_func('world', 'hello')它會打印world hello。傳遞kwargs的順序并不重要:

the_func('hello', 'world')# -> 'hello world'
the_func('world', 'hello')# -> 'world hello'
the_func(greeting='hello', thing='world') # -> 'hello world'
the_func(thing='world', greeting='hello') # -> 'hello world'
the_func('hello', thing='world')# -> 'hello world'

只要kwarg在位置參數(shù)之后,就可以混合和匹配位置參數(shù)和關(guān)鍵字參數(shù),以上就是我們在python教程中經(jīng)??吹降膬?nèi)容,下面我們繼續(xù)。

函數(shù)參數(shù)

我們將演示6個函數(shù)參數(shù)傳遞的方法,這些方法能夠覆蓋到所有的問題。

1、如何獲得所有未捕獲的位置參數(shù)

使用*args,讓它接收一個不指定數(shù)量的形參。

def multiply(a, b, args):
result = a * b
for arg in args:
result = result * arg
return result

在這個函數(shù)中,我們通常定義前兩個參數(shù)(a和b)。然后使用args將所有剩余參數(shù)打包到一個元組中??梢园?看作是獲取到了其他沒有處理的參數(shù),并將它們收集到一個名為“args”的元組變量中:

multiply(1, 2)# returns 2
multiply(1, 2, 3, 4)# returns 24

最后一次調(diào)用將值1賦給參數(shù)a,將2賦給參數(shù)b,并將arg變量填充為(3,4)。由于這是一個元組,我們可以在函數(shù)中循環(huán)它并使用這些值進行乘法!

2、如何獲得所有未捕獲的關(guān)鍵字參數(shù)

與*args類似,這次是兩個星號**kwargs

def introduce(firstname, lastname, **kwargs):
introduction = f"I am {firstname} {lastname}"
for key, value in kwargs.items():
introduction += f" my {key} is {value} "
return introduction

**kwargs關(guān)鍵字會將所有不匹配的關(guān)鍵字參數(shù)存儲在一個名為kwargs的字典中。然后可以像上面的函數(shù)一樣訪問這個字典。

 print(introduce(firstname='mike', lastname='huls'))
 # returns "I am mike huls"
 
 print(introduce(firstname='mike', lastname='huls', age=33, website='mikehuls.com'))
 # I am mike huls my age is 33 my website is overfit.cn
3、如果想只接受關(guān)鍵字參數(shù),那怎么設(shè)計

可以強制函數(shù)只接受關(guān)鍵字參數(shù)。

 def transfer_money(*, from_account:str, to_account:str, amount:int):
 print(f'Transfering ${amount} FORM {from_account} to {to_account}')
 
 transfer_money(from_account='1234', to_account='6578', amount=9999)
 # won't work: TypeError: transfer_money() takes 0 positional arguments but 1 positional argument (and 2 keyword-only arguments) were given
 transfer_money('1234', to_account='6578', amount=9999)
 # won't work: TypeError: transfer_money() takes 0 positional arguments but 3 were given
 transfer_money('1234', '6578', 9999)

在上面的函數(shù)中,*星號獲得了了所有不匹配的位置參數(shù),但是并沒有一個變量來接受它,也就是被忽略了。

4、如何設(shè)計函數(shù)只接受位置參數(shù)

下面是一個只允許位置參數(shù)的函數(shù)示例:

 def the_func(arg1:str, arg2:str, /):
 print(f'provided {arg1=}, {arg2=}')
 
 # These work:
 the_func('num1', 'num2')
 the_func('num2', 'num1')
 
 # won't work: TypeError: the_func() got some positional-only arguments passed as keyword arguments: 'arg1, arg2'
 the_func(arg1='num1', arg2='num2')
 # won't work: TypeError: the_func() got some positional-only arguments passed as keyword arguments: 'arg2'
 the_func('num1', arg2='num2')

函數(shù)定義中的/強制在它之前的所有參數(shù)都是位置參數(shù)。這并不意味著/后面的所有參數(shù)都必須是kwarg-only;這些可以是位置和關(guān)鍵字。

看到這個你肯定會想,為什么想要這個?這不會降低代碼的可讀性嗎?,我也覺得你說的非常正確,當定義一個非常明確的函數(shù)時,不需要關(guān)鍵字參數(shù)來指定它的功能。例如:

def exceeds_100_bytes(x, /) -> bool:
 return x.__sizeof__() > 100
 
 exceeds_100_bytes('a')
 exceeds_100_bytes({'a'})

在這個例子中,正在檢查'a'的內(nèi)存大小是否超過100字節(jié)。因為這個x對于我們來說他的名字不重要,在調(diào)用函數(shù)的時候不需要指定x= ' a '。比如說我們最常用的len,如果你調(diào)用len(__obj=[]) 這樣看起來是不是有點呆萌,因為len是這么定義的def len(__obj: Sized) -> int:

5、混合和匹配

作為一個例子,我們將看看前面討論過的len函數(shù)。這個函數(shù)只允許位置參數(shù)。我們將通過允許開發(fā)人員選擇是否計算重復(fù)項來擴展此函數(shù),比如用kwargs傳遞這個關(guān)鍵字:

 def len_new(x, /, *, no_duplicates=False):
 if (no_duplicates):
 return len(list(set([a for a in x])))
 return len(x)

想計算變量x的len,只能按位置傳遞x形參的參數(shù),因為它前面有一個/。no_duplicate參數(shù)必須與關(guān)鍵字一起傳遞,因為它跟在后面。讓我們看看這個函數(shù)都可以怎么調(diào)用:

print(len_new('aabbcc'))# returns 6
 print(len_new('aabbcc', no_duplicates=True))# returns 3
 print(len_new([1, 1, 2, 2, 3, 3], no_duplicates=False)) # returns 6
 print(len_new([1, 1, 2, 2, 3, 3], no_duplicates=True))# returns 3
 
 # Won't work: TypeError: len_() got some positional-only arguments passed as keyword arguments: 'x'
 print(len_new(x=[1, 1, 2, 2, 3, 3]))
 # Won't work: TypeError: len_new() takes 1 positional argument but 2 were given
 print(len_new([1, 1, 2, 2, 3, 3], True))
6、最后把它們合在一起

下面的函數(shù)是一個非常極端的例子,說明了如何組合前面討論的所有技術(shù):它強制前兩個參數(shù)以位置方式傳遞,接下來的兩個參數(shù)可以以位置方式傳遞,并且?guī)в嘘P(guān)鍵字,然后是兩個只有關(guān)鍵字的參數(shù),然后我們用**kwargs捕獲剩下的未捕獲的參數(shù)。

 def the_func(pos_only1, pos_only2, /, pos_or_kw1, pos_or_kw2, *, kw1, kw2, **extra_kw):
 # cannot be passed kwarg  can be passed 2 ways | --> can only be passed by kwarg
 print(f"{pos_only1=}, {pos_only2=}, {pos_or_kw1=}, {pos_or_kw2=}, {kw1=}, {kw2=}, {extra_kw=}")

調(diào)用方式如下:

# works (pos_or_kw1 & pow_or_k2 can be passed positionally and by kwarg)
 pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2', extra_kw={}
 pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2', extra_kw={}
 pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2', extra_kw={'kw_extra1': 'extra_kw1'}
 
 # doesnt work, (pos1 and pos2 cannot be passed with kwarg)
 # the_func(pos_only1='pos1', pos_only2='pos2', pos_or_kw1='pk1', pos_or_kw2='pk2', kw1='kw1', kw2='kw2')
 
 # doesnt work, (kw1 and kw2 cannot be passed positionally)
 # the_func('pos1', 'pos2', 'pk1', 'pk2', 'kw1', 'kw2')

關(guān)于“Python中函數(shù)參數(shù)傳遞方法有哪些”的內(nèi)容就介紹到這里了,感謝大家的閱讀。如果想了解更多行業(yè)相關(guān)的知識,可以關(guān)注億速云行業(yè)資訊頻道,小編每天都會為大家更新不同的知識點。

向AI問一下細節(jié)

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

AI