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

3

我有一个自定义的字典类 (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)

编辑:(我的评论代码,不确定这是否是正确的方法,特别是如果有多个keyname参数需要放入self而不是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 

你的意思是像这样 __init__(self, custom_name, *args, **kwargs) 吗? - netcoder
类似于__init__(self, custom_name=None, *args, kwargs)的写法,但是在默认参数之前不能有定义的名称。我考虑检查kwargs中是否存在'custom_name',如果存在,则将其从传递给字典的kwargs中删除,否则将custom_name设置为None。想知道是否有标准的做法。 - user3467349
1个回答

3

在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")

是的,我对Python2的方法也做了同样的事情 - 不过我不知道在Python3中可以在*args之后**kwargs之前使用custom_name = None,我会转换到那个方法,谢谢。 - user3467349

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接