簡體   English   中英

Python:使用* args ** kwargs傳遞可選的命名變量

[英]Python: passing an optional named variable with *args **kwargs

我有一個自定義的dict類( collections.MutablMapping ),實際的對象有點復雜,但我的問題很簡單,如何將自定義參數傳遞到*args **kwargs之外的__init__方法去dict()

class TestDict(collections.MutableMapping):
    def __init__(self, *args, **kwargs):
        self.store = dict()
        self.update(dict(*args, **kwargs)) 
        self.custom_name = None #how to pass custom name outside of the dict args? 
    def __getitem__(self, key):
        return self.store[key]
    def __setitem__(self, key, value):
        self.store[key] = value
    def __delitem__(self, key):
        del self.store[key]
    def __len__(self):
        return len(self.store)
    def __iter__(self):
        return iter(self.store)
    def __repr__(self): 
        return str(self.store)

編輯:(我的評論的代碼,再次不確定這是否是正確的方式,特別是如果有一個多個鍵名參數放入自己而不是dict()):

def __init__(self, *args, **kwargs): 
    try: custom_name = kwargs.pop('custom_name')
    except: custom_name = None
    self.store = dict()
    self.update(dict(*args, **kwargs)) 
    self.custom_name = custom_name 

在Python 3中,您可以:

def __init__(self, *args, custom_name=None, **kwargs):
    self.custom_name = custom_name

    # do your stuff...

在Python 2中,您可以:

def __init__(self, *args, **kwargs):
    try:
        self.custom_name = kwargs["custom_name"]
        del kwargs["custom_name"]
    except:
        self.custom_name = None

    # do your stuff...

任何一個版本都會像這樣實例化:

d = TestDict({"spam": "egg"}, custom_name="my_custom_dict")

暫無
暫無

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

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