gpt4 book ai didi

Python:检测某个变量是否输入到函数参数中

转载 作者:行者123 更新时间:2023-12-01 04:32:39 26 4
gpt4 key购买 nike

如何让函数识别某个变量是否作为参数输入?

我想在函数中输入多个变量,如果它们存在,则将相应的二进制变量作为 True 返回给程序。

#variables to test: x, y, z

def switch(*variables):
for var in list(variables):
#detect if var is the variable x:
switch_x = True
#detect if var is the variable y:
switch_y = True
#detect if var is the variable z:
switch_z = True

switch(x, y, z)

if switch_x is True:
#Do something

请注意,我希望测试变量本身是否已输入到函数中。不是变量包含的

最佳答案

不,这不可能用 *args 做到,但您可以使用 **kwargs实现类似的行为。您将函数定义为:

def switch(**variables):
if 'x' in variables:
switch_x = True
if 'y' in variables:
switch_y = True
if 'z' in variables:
switch_z = True

并调用如下:

switch(x=5, y=4)
switch(x=5)
# or
switch(z=5)

关于Python:检测某个变量是否输入到函数参数中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32166799/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com