对Python中向函数传递参数的位置和关键字方式有一些疑问

2024-09-27 21:26:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下与认证相关的问题

我有一个简单的功能:

def fun(a,b):
    return a + b

这被称为:

res = fun(1,2)

在研究材料中,对“传递论点的方式是什么”这一问题给出以下答案:关键词

我认为这个答案是错误的,因为根据:https://www.techbeamers.com/python-function/

关键字方式应该包含以下内容:

res = fun(a=1, b=2)

我的推理正确吗

其他选择包括:

  • 命名
  • 位置的
  • 连续的

我的想法是,在这种情况下是定位的

是我的推理正确还是我遗漏了什么


Tags: 答案https功能comreturndefwww错误
2条回答

如果您想要默认参数,您应该添加以下内容

def fun(a=1,b=1)
       return a+b

因此,如果您在没有参数的情况下调用fun,默认值将使代码不会出错

>>> fun()
2

本教程给出的答案是正确的,它们是位置关键字参数。考虑下面的例子:

>>> def f(a,b):
        print(a) 
>>> f(2,3)
2
>>> f(b=3, a=2)
2

Python Glossary (parameter)开始:

A named entity in a function (or method) definition that specifies an argument (or in some cases, arguments) that the function can accept. There are five kinds of parameter:

  • positional-or-keyword: specifies an argument that can be passed either positionally or as a keyword argument. This is the default kind of parameter, for example foo and bar in the following:

    def func(foo, bar=None): ...

  • positional-only: specifies an argument that can be supplied only by position. Python has no syntax for defining positional-only parameters. However, some built-in functions have positional-only parameters (e.g. abs()).

  • keyword-only: specifies an argument that can be supplied only by keyword. Keyword-only parameters can be defined by including a single var-positional parameter or bare * in the parameter list of the function definition before them, for example kw_only1 and kw_only2 in the following:

    def func(arg, *, kw_only1, kw_only2): ...

从另一个意义上说,“位置”也总是正确的,因为关键字参数是作为“幕后”位置参数计算的。从Python language reference (Calls)开始:

If keyword arguments are present, they are first converted to positional arguments, as follows [...]

同样的docs也给出了位置参数而非关键字参数的示例:

CPython implementation detail: An implementation may provide built-in functions whose positional parameters do not have names, even if they are ‘named’ for the purpose of documentation, and which therefore cannot be supplied by keyword. In CPython, this is the case for functions implemented in C that use PyArg_ParseTuple() to parse their arguments.

相关问题 更多 >

    热门问题