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。对不起,如果我的措辞有点误导。