首页 > 编程知识 正文

Python基础positional argument vs keyword argument

时间:2023-05-06 15:21:34 阅读:272875 作者:34

python强大的类型推导,有时也会带来一些副作用,比如有时编译器会报如下错误:

TypeError: Function takes at most 1 positional arguments (2 given)# 函数最多接受一个位置参数,却提供了两个

所谓positional argument位置参数,是指用相对位置指代参数。关键字参数(keyword argument),见名知意使用关键字指代参数。位置参数或者按顺序传递参数,或者使用名字,自然使用名字时,对顺序没有要求。

A positional argument is a name that is not followed by an equal assign(=) and default value.

A keyword argument is followed by an equal sign and an expression that gives its default value.

以上的两条引用是针对函数的定义(definition of the function)来说的,与函数的调用(calls to the function),也即在函数的调用端,既可以使用位置标识参数,也可使用关键字。

def foo(x, y): return x*(x+y)print(foo(1, 2)) # 3, 使用positional argumentprint(foo(y=2, x=1)) # 3,named argument

一个更完备的例子如下:

def fn(a, b, c=1): return a*b+cprint(fn(1, 2)) # 3, positional(a, b) and default(c)print(fn(1, 2, 3)) # 5, positional(a, b)print(fn(c=5, b=2, a=2)) # 9, named(b=2, a=2)print(fn(c=5, 1, 2)) # syntax errorprint(fn(b=2, a=2)) # 5, named(b=2, a=2) and defaultprint(fn(5, c=2, b=1)) # 7, positional(a), named(b).print(fn(8, b=0)) # 1, positional(a), named(b), default(c=1)

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。