[英]Packing function argument
我想調用一個在單個變量內發送多個參數的函數。
換句話說,我想對Test(some_var)
與示例中x1
相同的結果。
class Test:
def __init__(self, one, two=None):
self.one = one
if two is not None:
self.two = two
tup = 'a', 'b'
lst = ['a', 'b']
x1 = Test('a', 'b')
x2 = Test(tup)
x3 = Test(lst)
您必須使用運算符*
解壓縮參數:
Test(*tup)
順便說一句,當您要按位置分配參數時,使用運算符*
。 如果要按名稱分配參數,則可以在字典中使用運算符**
:
def foo(a, b):
print(a, b)
kwargs = {'b': 20, 'a': 0}
foo(**kwargs) # 0 20
您可以使用*
運算符解壓縮元組或列表:
class Test:
def __init__(self, one, two=None):
self.one = one
if two is not None:
self.two = two
tup = 'a', 'b'
lst = ['a', 'b']
x1 = Test('a', 'b')
x2 = Test(*tup) # unpack with *
x3 = Test(*lst) # unpack with *
print(vars(x1) == vars(x2) == vars(x3)) # True
如果您有關鍵字參數和一個dict
,則還可以用兩個*
s來解壓縮該dict:
class Test:
def __init__(self, one=None, two=None):
self.one = one
if two is not None:
self.two = two
kwargs = {'one': 'a', 'two': 'b'}
x1 = Test('a', 'b')
x2 = Test(**kwargs)
print(vars(x1) == vars(x2)) # True
看這里 。
拆包運算符的用途非常廣泛,不僅限於函數參數。 例如:
>>> [*range(4), 4]
[0, 1, 2, 3, 4]
>>> {'x': 1, **{'y': 2}}
{'x': 1, 'y': 2}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.