本文介绍了Python可选,位置和关键字参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我上的一堂课

class metadict(dict):
    def __init__(self, do_something=False, *args, **kwargs)
        if do_something:
            pass
        super(metadict,self).__init__(*args,**kwargs)

这个想法是封装字典并添加带有特殊关键字的某些功能.尽管您无法在创建时添加字典,但该字典仍然可以容纳do_something.在所有其他方面,它的行为就像普通字典一样.

The idea is to encapsulate a dictionary and add some functionality with a special keyword. The dictionary can still hold do_something though you can't add it at creation time. For all other aspects it behaves just like a normal dictionary.

无论如何,问题在于我给args的任何东西都是通过将第一个值分配给do_something而开始的,而这并不是我想要的.

Anyway, the problem is that whatever I give to args it starts by assigning the first value to do_something which is not what I want.

我现在要做的是:

class metadict(dict):
    def __init__(self, do_something=False, *args, **kwargs)
        if not isinstance(do_something, bool):
            args = list(args)
            args.append(do_something)
        elif do_something:
            pass
        super(metadict,self).__init__(*args,**kwargs)

但这对我来说并不正确.我还可以检查kwargs中的do_something值,但这会更糟,因为我搞砸了签名,删除了有用的信息...

But it doesn't look right to me. I could also check for the do_something value in kwargs, but it will be worse, since I mess with the signature removing useful information...

python中是否可以安全使用可选参数,位置参数和关键字参数?如果没有,还有其他更简单的解决方法吗?

Is there any way in python to use optional, positional and keyword arguments safely?If not are there other simpler workarounds?

我使用的是python 2.6

I'm on python 2.6

推荐答案

它是新功能Python 3 . Python 2中最好的解决方法是

It's new in Python 3. The best workaround in Python 2 is

def foo(*args, **kwargs):
    do_something = kwargs.pop("do_something", False)

您看到的行为之所以发生,是因为Python试图巧妙地匹配参数,因此例如,如果您传递太多的位置参数,它将使关键字参数位置固定.

The behaviour you see happens because Python tries to be clever in matching up arguments, so for instance it will make a keyword argument positional if you pass too many positional arguments.

PS为什么不将其存储为metadict的属性而不是dict中的条目?

PS why not store it as an attribute of metadict instead of as an entry in the dict?

这篇关于Python可选,位置和关键字参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 22:09