Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/366.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python:检测函数参数中是否输入了某个变量_Python - Fatal编程技术网

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

Python:检测函数参数中是否输入了某个变量,python,Python,如何使函数识别某个变量是否作为参数输入 我想在函数中输入一些变量,如果它们存在,将相应的二进制变量作为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 varia

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

我想在函数中输入一些变量,如果它们存在,将相应的二进制变量作为
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
实现,但您可以使用它来实现类似的行为。您将函数定义为:

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)

传递的是值,而不是原始变量。不用了,谢谢你。但这是在寻找字符串的一部分,不是吗?我使用的变量从一开始就被设置为
False
,如果输入到函数中,则应该切换到
True
。尽管也许一个解决办法是将变量设置为以字符串形式包含其名称?因此:
x='x'。。。如果变量中的
'x:
否,则不是。仔细阅读有关
**kwargs
的链接问题。当您调用
开关(x=5,y=4)
时,您的
变量
将成为一个包含两项的
dict
,如
{x':5,'y':4}
。和
中的
,操作员检查此
目录中是否存在具有特定名称的项(使用
x=any_值有效地检查是否传入了任何值)。发件人:
输入d
如果
d
有键,则返回True,否则返回False。对不起,如果我的措辞有点误导。