python - 打包函数参数
问题描述
我想调用一个在单个变量中发送多个参数的函数。
换句话说,我想做Test(some_var)
与示例中相同的结果x1
。
class Test:
def __init__(self, one, two=None):
self.one = one
if two is not None:
self.two = two
tup = 'a', 'b'
lst = ['a', 'b']
x1 = Test('a', 'b')
x2 = Test(tup)
x3 = Test(lst)
解决方案
您必须使用 operator 解压缩参数*
:
Test(*tup)
顺便说一句,*
当您想按位置分配参数时,使用运算符。如果要按名称分配参数,可以将 operator **
in 与字典一起使用:
def foo(a, b):
print(a, b)
kwargs = {'b': 20, 'a': 0}
foo(**kwargs) # 0 20
推荐阅读
- python - 如何将 torch.scatter_add 更改为 tensorflow 函数
- django - Django & Postgres - 索引行大小超过 btree 版本 4 最大值
- javascript - 如何验证纯 Javascript 中的多个错误?
- google-classroom - Google Classroom API 使用(获取有关课程的信息)
- python - 如何向我的 PyTorch 模型添加(假)可调用参数?
- cron - 如何让 Node JS 服务器在共享主机上运行
- javascript - 如何将字符串转换为 Int 以防止无效值错误?
- python - Discord.py 任务未运行
- regex - 正则表达式删除 !IMAGE 和 [] 括号之间的字符串
- javascript - 如何将文件路径(到硬盘文件夹)放入 js 变量中,而不会出现“无效或意外令牌”