python - 在正文中传播函数参数
问题描述
可能是一个愚蠢的问题,但出于好奇而问
在python中,我可以传播*args
并**kwargs
在函数的签名中
def my_func(foo, bar):
print(f"foo={foo}, bar={bar}")
my_func(1, 2) # 1 2
my_func(1, bar=2) # 1 2
my_func(foo=1, bar=2) # 1 2
是否可以将它传播到这样的函数体中?
def my_func(*args, **kwargs):
foo, bar = *args, **kwargs <=== Something like this
print(f"foo={foo}, bar={bar}")
my_func(1, 2) # 1 2
my_func(1, bar=2) # 1 2
my_func(foo=1, bar=2) # 1 2
解决方案
args
是一个元组,不是foo
.
kwargs
是 a dict
,而不是 的值bar
。
def my_func(*args, **kwargs):
foo = args[0] # Assumes there is at least one positional argument
bar = kwargs['bar'] # Assumes there is a keyword argument named bar
print(f"foo={foo}, bar={bar}")
my_func(1, bar=2) # 1 2
如果您放弃使用签名,则必须明确说明位置参数到名称的映射。例如,
def my_func(*args, **kwargs):
if len(args) == 0 and `foo` not in kwargs:
raise TypeError("Missing argument for 'foo'")
else:
try:
foo = args[0]
except IndexError:
foo = kwargs['foo']
if len(args) == 1 and `bar` not in kwargs:
raise TypeError("Missing argument for 'bar'")
else:
try:
bar = args[1]
except IndexError:
bar = kwargs['bar']
....
在这里,我假设位置参数应该优先于关键字参数。您还可以使关键字参数优先
def my_func(*args, **kwargs):
if len(args) == 0 and `foo` not in kwargs:
raise TypeError("Missing argument for 'foo'")
else:
try:
foo = kwargs['foo'
except IndexError:
foo = args[0]
if len(args) == 1 and `bar` not in kwargs:
raise TypeError("Missing argument for 'bar'")
else:
try:
bar = kwargs['bar']
except IndexError:
bar = args[1]
....
或继续将尝试同时使用两者视为错误:
def my_func(*args, **kwargs):
if len(args) == 0 and `foo` not in kwargs:
raise TypeError("Missing argument for 'foo'")
elif len(args) > 0 and `foo` in kwargs:
raise TypeError("Multiple attempts to assign foo")
else:
try:
foo = args[0]
except IndexError:
foo = kwargs['foo']
if len(args) == 1 and `bar` not in kwargs:
raise TypeError("Missing argument for 'bar'")
elif len(args) > 1 and `bar` in kwargs:
raise TypeError("Multiple attempts to assign bar")
else:
try:
bar = args[1]
except IndexError:
bar = kwargs['bar']
....
推荐阅读
- docker - 创建 docker 容器时出现错误消息
- azure - while循环中的Powershell函数第一次不输出结果,但第二次输出,两次
- f# - 我可以在 F# 的有区别的联合中直接使用代表吗?
- c++ - 在 Pybind11 中使用自动转换
- android - 从 Listview (Fragment) 的 onClick 方法启动 Activity
- c# - 在一个查询中执行 2 次搜索
- java - 填充和打印个人 LinkedList 复制的元素
- c - 将字符串转换为 Int 并再次返回字符串 C
- r - 如何尊重 R ggplot2 中离散/组变量的定量性质?
- sql-server - 更新和插入语句之间的存储过程“忘记”字段