除非用户另有说明,否则如何将函数中的参数设置为 False?

How to set an argument in a function to False unless the user specifies otherwise?

我有一个包含两个参数的函数。函数本身做什么并不重要。重要的是,在调用函数时,我想将第二个参数设置为默认布尔值 False 值。

所以我们假设如果第二个参数是 False 或未指定 True 它将打印与函数调用中的 True 不同的行。

事情是这样的。我希望第二个参数默认设置为 False,即使用户在调用函数时将其指定为 False,因此,当用户指定它时,这将仅是 True .

示例:

def example(stringy, printable):
    if printable == True:
        print(stringy, "Printable is set to True")
    else:
        print(stringy, "Printable is set to False")

example("A")

问题是,如果我仅将函数调用为 example("Hello World"),我将得到

Traceback (most recent call last) line 7, in <module>
    example("A")
TypeError: example() missing 1 required positional argument: 'printable'

那么有没有办法让 printable 默认设置为 False 除非用户在调用函数时更改它?

在python中,你想要的是使用关键字参数;这些总是采用默认值。语法几乎与您已有的相同:

def example(stringy, printable=False):
    if printable == True:
        print(stringy, "Printable is set to True")
    else:
        print(stringy, "Printable is set to False")

然后可以通过以下任何一种方式调用该函数,结果相同:

example("A")
example("A", False)
example("A", printable=False)

您只需在 def 中使用变量设置参数。

def example(stringy, printable = False):
if printable == True:
    print(stringy, "Printable is set to True")
else:
    print(stringy, "Printable is set to False")

这将使 printable 默认设置为 False,除非用户在调用它时更改它

example("A")
    A Printable is set to False

example("A", True)
    A Printable is set to True