我想知道是否可以确定是否在Python中传递了具有默认值的函数参数。 例如,dict.pop是如何工作的?

>>> {}.pop('test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented

pop方法如何确定第一次没有传递默认返回值?这是否只能在C中完成?

由于

有帮助吗?

解决方案

我猜你的意思是“关键字参数”,当你说“命名参数”时。 dict.pop()不接受关键字参数,所以这部分问题没有实际意义。

>>> {}.pop('test', d=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pop() takes no keyword arguments

也就是说,检测是否提供参数的方法是使用 * args ** kwargs 语法。例如:

def foo(first, *rest):
    if len(rest) > 1:
        raise TypeError("foo() expected at most 2 arguments, got %d"
                        % (len(rest) + 1))
    print 'first =', first
    if rest:
        print 'second =', rest[0]

通过一些工作,并且使用 ** kwargs 语法,也可以完全模拟python调用约定,其中参数可以通过位置或名称提供,并且参数提供多次(按位置和名称)导致错误。

其他提示

约定通常是使用 arg = None 并使用

def foo(arg=None):
    if arg is None:
        arg = "default value"
        # other stuff
    # ...

检查是否通过了。允许用户传递 None ,这将被解释为参数传递。

你可以这样做:

def isdefarg(*args):
    if len(args) > 0:
        print len(args), "arguments"
    else:
        print "no arguments"

isdefarg()
isdefarg(None)
isdefarg(5, 7)

有关完整信息,请参阅电话上的Python文档。

def f(one, two=2):
   print "I wonder if", two, "has been passed or not..."

f(1, 2)

如果这是你问题的确切含义,我认为没有办法区分默认值中的2和已经传递的2。即使在检查中,我也没有找到如何实现这种区别模块。

我不确定我是否完全理解你想要的是什么;但是:

def fun(arg=Ellipsis):
    if arg is Ellipsis:
        print "No arg provided"
    else:
        print "arg provided:", repr(arg)

这样做你想要的吗?如果没有,那么正如其他人所建议的那样,你应该使用 * args,** kwargs 语法声明你的函数,并检查kwargs dict中是否存在参数。

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top