为什么我们需要在函数中的第二个参数之后初始化参数?

2024-05-17 05:29:33 发布

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

我正在做代码战的初学者Kata,我对我们使用函数的方式感到困惑

它有3个论点;a、 b和保证金。结果我们必须将margin初始化为0,否则Python找不到它。但是为什么我们不需要初始化a或b呢

函数是close_margin(a, b, margin = 0): 为什么不close_margin(a = 0, b = 0, margin = 0):

完整代码如下:

def close_compare(a, b, margin):

    if margin == '':

        margin = 0

    if a < b:

        return -1

    if a > b:

        return 1

    difference = a - b

    if margin > difference or margin == difference:

        return 0

产生的错误代码是:

Traceback (most recent call last):
File "main.py", line 4, in <module>
test.assert_equals(close_compare(4, 5), -1)
TypeError: close_compare() missing 1 required positional argument: 'margin'

Tags: or函数代码margin保证金closereturnif
1条回答
网友
1楼 · 发布于 2024-05-17 05:29:33

参数的主要用途是在调用函数时接受参数。但是,在定义函数时,可以使用默认值来“初始化”参数。如果在调用时没有提供参数,则将使用默认值,就像您显式提供了它一样

给出了这样的定义

def foo(a, b, margin=0):
    ...

以下调用相同:

foo(3, 5)  # Use the default value of 0 for the third parameter
foo(3, 5, 0)  # Provide a value of 0 for the third parameter

但是,一个不相关的特性是能够提供关键字参数,它允许您按名称而不是位置指定值。非关键字参数首先出现,并按参数在定义中出现的顺序分配给参数。关键字参数可以以任何顺序出现。以下所有条件都是等效的:

# All positional arguments
foo(3, 5, 0)
# Two positional, one keyword
foo(3, 5, margin=0)
# One positional, two keyword
foo(3, b=5, margin=0)
foo(3, margin=0, b=5)
# No positional, all keyword
foo(a=3, b=5, margin=0)
foo(b=5, margin=0, a=3)
foo(a=3, margin=0, b=5)
foo(b=5, a=3, margin=0)
foo(margin=0, a=3, b=5)
foo(margin=0, b=5, a=3)

相关问题 更多 >