Jak*_*ake 14 python default-value named-parameters
我想知道是否可以确定是否在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
Run Code Online (Sandbox Code Playgroud)
pop方法如何确定第一次没有传递默认返回值?这是否只能在C中完成?
谢谢
Mar*_*rot 12
惯例通常是使用arg=None和使用
def foo(arg=None):
if arg is None:
arg = "default value"
# other stuff
# ...
Run Code Online (Sandbox Code Playgroud)
检查是否通过了.允许用户传递None,这将被解释为没有传递参数.
我猜你的意思是"关键字参数",当你说"命名参数"时.dict.pop()不接受关键字参数,所以这部分问题没有实际意义.
>>> {}.pop('test', d=None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: pop() takes no keyword arguments
Run Code Online (Sandbox Code Playgroud)
也就是说,检测是否提供参数的方法是使用*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]
Run Code Online (Sandbox Code Playgroud)
通过一些工作,并使用**kwargs语法也可以完全模拟python调用约定,其中参数可以通过位置或名称提供,并且多次提供的参数(按位置和名称)会导致错误.
| 归档时间: |
|
| 查看次数: |
13595 次 |
| 最近记录: |