Python 啪啪打在中间
Python splat-in-the-middle
你可以将splat参数放在中间而不是最后(似乎只在python 3中):
import functools
def wierd_sum(use_str_cat=False, *args, use_product=False):
if use_str_cat:
return ''.join([str(a) for a in args])
elif use_product:
return functools.reduce(lambda a,b : a*b, args)
else:
return functools.reduce(lambda a,b : a+b, args)
现在你如何使用上述功能?
print(wierd_sum(1, 2, 3)) # 23 -> Concatenation, 1 counts as True.
print(wierd_sum(False, 2, 3, 4, 5, True)) # 15 -> Addition, True counts as 1.
print(wierd_sum(False, 2, 3, 4, 5, use_product=True)) # 120 -> Multiplication 2*3*4*5
print(wierd_sum(use_str_cat=True, 1, 2, 3)) # SyntaxError: positional argument follows keyword argument.
print(wierd_sum(1, 2, 3, use_str_cat=False)) # TypeError: wierd_sum() got multiple values for argument 'use_str_cat'
我的问题是,有没有 ever, EVER 这样做的理由这种事?
这是为了 keyword only arguments; similar to positional-only arguments (comparison here).
理想情况下,除非您确实需要可变参数,否则您应该省略名称以禁止提供可变参数:
def my_func(a, *, keyword_only=True):
pass
my_func(1, 2) # TypeError: my_func() takes 1 positional argument but 2 were given
my_func(1, keyword_only=2) # Fine
你可以将splat参数放在中间而不是最后(似乎只在python 3中):
import functools
def wierd_sum(use_str_cat=False, *args, use_product=False):
if use_str_cat:
return ''.join([str(a) for a in args])
elif use_product:
return functools.reduce(lambda a,b : a*b, args)
else:
return functools.reduce(lambda a,b : a+b, args)
现在你如何使用上述功能?
print(wierd_sum(1, 2, 3)) # 23 -> Concatenation, 1 counts as True.
print(wierd_sum(False, 2, 3, 4, 5, True)) # 15 -> Addition, True counts as 1.
print(wierd_sum(False, 2, 3, 4, 5, use_product=True)) # 120 -> Multiplication 2*3*4*5
print(wierd_sum(use_str_cat=True, 1, 2, 3)) # SyntaxError: positional argument follows keyword argument.
print(wierd_sum(1, 2, 3, use_str_cat=False)) # TypeError: wierd_sum() got multiple values for argument 'use_str_cat'
我的问题是,有没有 ever, EVER 这样做的理由这种事?
这是为了 keyword only arguments; similar to positional-only arguments (comparison here).
理想情况下,除非您确实需要可变参数,否则您应该省略名称以禁止提供可变参数:
def my_func(a, *, keyword_only=True):
pass
my_func(1, 2) # TypeError: my_func() takes 1 positional argument but 2 were given
my_func(1, keyword_only=2) # Fine