简体   繁体   中英

Python: passing an optional named variable with *args **kwargs

I have a custom dict class ( collections.MutablMapping ),the actual object is somewhat more complicated, but the question I have is rather simple, how can I pass custom parameters into the __init__ method outside of *args **kwargs that go to 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)

Edit: (the code for my comment, again not sure if this is the correct way of doing it, especially if one had multiple keyname arguments to put into self rather than 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 

In Python 3, you'd do:

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

    # do your stuff...

In Python 2, you'd do:

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

    # do your stuff...

Either version will be instantiated like so:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM