简体   繁体   English

Python:使用* args ** kwargs传递可选的命名变量

[英]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() 我有一个自定义的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)

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() ): 编辑:(我的评论的代码,再次不确定这是否是正确的方式,特别是如果有一个多个键名参数放入自己而不是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: 在Python 3中,您可以:

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

    # do your stuff...

In Python 2, you'd do: 在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...

Either version will be instantiated like so: 任何一个版本都会像这样实例化:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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