“关键字参数”与常规参数有何不同?所有的参数不能被传递为name=value而不是使用位置语法吗?
当前回答
只需补充/添加一种方法来定义参数的默认值,当调用函数时,这些参数没有在关键字中赋值:
def func(**keywargs):
if 'my_word' not in keywargs:
word = 'default_msg'
else:
word = keywargs['my_word']
return word
叫它:
print(func())
print(func(my_word='love'))
你会得到:
default_msg
love
阅读更多关于python中的*args和**kwargs的信息:https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3
其他回答
我正在寻找一个使用类型注释的默认kwargs的示例:
def test_var_kwarg(a: str, b: str='B', c: str='', **kwargs) -> str:
return ' '.join([a, b, c, str(kwargs)])
例子:
>>> print(test_var_kwarg('A', c='okay'))
A B okay {}
>>> d = {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', c='c', b='b', **d))
a b c {'f': 'F', 'g': 'G'}
>>> print(test_var_kwarg('a', 'b', 'c'))
a b c {}
还有最后一个重要的语言特性。考虑以下函数:
def foo(*positional, **keywords):
print "Positional:", positional
print "Keywords:", keywords
*positional参数将存储传递给foo()的所有位置参数,不限制提供的数量。
>>> foo('one', 'two', 'three')
Positional: ('one', 'two', 'three')
Keywords: {}
**keywords参数将存储任何关键字参数:
>>> foo(a='one', b='two', c='three')
Positional: ()
Keywords: {'a': 'one', 'c': 'three', 'b': 'two'}
当然,你可以同时使用这两个词:
>>> foo('one','two',c='three',d='four')
Positional: ('one', 'two')
Keywords: {'c': 'three', 'd': 'four'}
这些特性很少被使用,但偶尔它们非常有用,知道哪些参数是位置参数或关键字是很重要的。
我很惊讶没有人提到你可以混合位置参数和关键字参数,使用*args和**kwargs来做这样的鬼鬼祟祟的事情:
def test_var_kwargs(farg, **kwargs):
print "formal arg:", farg
for key in kwargs:
print "another keyword arg: %s: %s" % (key, kwargs[key])
这允许您使用任意关键字参数,这些参数可能包含您不想在前面定义的键。
使用Python 3,你可以同时拥有必需的和非必需的关键字参数:
可选:(为参数'b'定义的默认值)
def func1(a, *, b=42):
...
func1(value_for_a) # b is optional and will default to 42
必需(没有为参数'b'定义默认值):
def func2(a, *, b):
...
func2(value_for_a, b=21) # b is set to 21 by the function call
func2(value_for_a) # ERROR: missing 1 required keyword-only argument: 'b'`
这可以帮助在你有许多相似的参数,特别是如果他们是相同类型的情况下,在这种情况下,我更喜欢使用命名参数或我创建一个自定义类,如果参数属于一起。
只需补充/添加一种方法来定义参数的默认值,当调用函数时,这些参数没有在关键字中赋值:
def func(**keywargs):
if 'my_word' not in keywargs:
word = 'default_msg'
else:
word = keywargs['my_word']
return word
叫它:
print(func())
print(func(my_word='love'))
你会得到:
default_msg
love
阅读更多关于python中的*args和**kwargs的信息:https://www.digitalocean.com/community/tutorials/how-to-use-args-and-kwargs-in-python-3
推荐文章
- Numpy Max vs amax vs maximum
- 我应该在.gitignore文件中添加Django迁移文件吗?
- 每n行有熊猫
- 实例属性attribute_name定义在__init__之外
- 如何获取在Python中捕获的异常的名称?
- 第一次出现的值大于现有值的Numpy
- 如何从Python函数中返回两个值?
- 前一个月的Python日期
- Python中方括号括起来的列表和圆括号括起来的列表有什么区别?
- Python日志记录不输出任何东西
- 每n秒运行特定代码
- SQLAlchemy是否有与Django的get_or_create等价的函数?
- 如何将python datetime转换为字符串,具有可读格式的日期?
- 美丽的汤和提取div及其内容的ID
- 在Python中重置生成器对象