簡體   English   中英

python dict構造函數的混淆用法

[英]confusing usage of construction function of python dict

當我在https://github.com/ansible/ansible/blob/devel/lib/ansible/module_utils/common/collections.py 中閱讀 ansible 的源代碼時,我發現了下面的代碼片段。

class ImmutableDict(Hashable, Mapping):
    """Dictionary that cannot be updated"""
    def __init__(self, *args, **kwargs):
        self._store = dict(*args, **kwargs)

我嘗試將上面使用的相同語法與下面的代碼一起使用,但失敗了。

args = ("name", "jone", "sex", "male")
kwargs = {
    "age": 13,
    "job": "software enginner"
}
d = dict(*args, **kwargs)
print(d)

### error msg
Traceback (most recent call last):
  File "/Users/steveguan/code/Work/Test/test_dict.py", line 41, in <module>
    d = dict(*args, **kwargs)
TypeError: dict expected at most 1 arguments, got 4

我嘗試閱讀https://docs.python.org/3/library/stdtypes.html#dict 中的官方文檔,文檔顯示用法不對。

(*args)在我們從函數參數中解包參數時使用。 你不需要使用它。

def d(*arr):
    return dict(*arr)

arr = [(1,2),(3,4)]
d(arr)

這與

arr = [(1,2),(3,4)]
dict(arr)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM