我想知道是否可以确定在 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 中完成的事情吗?
谢谢
最佳答案
惯例通常是使用arg=None
和使用
def foo(arg=None):
if arg is None:
arg = "default value"
# other stuff
# ...
检查是否通过。允许用户传递 None
,这将被解释为参数未传递。
关于python - 确定是否传递了命名参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/255429/