python - 函数调用和变量

标签 python python-3.x

def func(a, b, c, d): print(a, b, c, d)

func(1, c=3, *(2,), **{'d':4})
func(1, c=3, 2, **{'d':4})

为什么前者调用有效而后者无效?我的意思是第一个不应该也返回错误吗? * 不只是解压一个可迭代对象吗?

最佳答案

位置参数必须始终出现在命名和解压缩参数之前。

在表达式中:

func(1, c=3, 2, **{'d':4})

2 是一个位置参数,而 c=3 是一个命名参数。这样写是无效的。您必须将命名参数移到所有 位置参数之后。

func(1, 2, c=3, **{'d':4})

另一方面,表达式:

func(1, c=3, *(2,), **{'d':4})

有效。 1 是这里唯一的位置参数。 c=3 是命名参数,*(2,)**{'d':4} 被解压。只要位置参数在前,都有效。

关于python - 函数调用和变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25511554/

相关文章:

python - python中如何过滤掉数组中不按特定顺序排列的元素

python - 我想在 python 中制作括号检查器来计算错误的括号

python - 不同的实例是否共享类中声明的相同方法?

python - 使用 python3.9 的 gdbm 无法打开使用 python 3.6 的 gdbm 创建的文件

python - 从列表中的字符串中删除\xa0

python - 添加 selenium webdriver 作为 python 项目依赖

python - 使用 BlackMagic 卡使用 Opencv 捕获帧(强度穿梭)

python - Selenium Python : Check that JS variable is true

python - 正则表达式 : replace the suffix of a string ending in '.js' but not 'min.js'

python - 当停止未知时,如何使用 RangeIndex 重新标记从 1 开始的 Pandas Dataframe?