如果输入了某个function作为参数,如何使variable识别?

我想在函数中输入一些变量,如果存在,请将相应的二进制变量作为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 - Python:检测是否将某些变量输入到函数参数中,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/32166799/

10-14 17:23
查看更多