【问题标题】:Checking the truthfulness of a keyword argument passed to a function does not work as expected - why? [duplicate]检查传递给函数的关键字参数的真实性不能按预期工作 - 为什么? [复制]
【发布时间】:2019-03-01 00:25:19
【问题描述】:

我知道 how to check 如果我键入 **kwargs 存在。现在我想检查传递给函数的参数的值。

def examplefunc(x,y,**kwargs):

    print(kwargs['extraarg'])
    if 'extraarg' in kwargs == True:
        print(kwargs['extraarg'])
        print("This is not printed")
    
    if 'extraarg' in kwargs: print("This is printed")
    
examplefunc(3,2,extraarg=True)   

输出:

是的

这是打印出来的

为什么不打印This is not printed'extraarg' in kwargs 是假的。那么为什么要继续打印This is printed


我也尝试用if 'extraarg' == True: 替换行if 'extraarg' in kwargs == True,但输出仍然缺少This is not printed

【问题讨论】:

  • 链接运算符比较...尝试不使用==True 或类似if '(extraarg' in kwargs) == True
  • @Jean-FrançoisFabre 你的意思是试试if ('extraarg' in kwargs)==True
  • 是的,在给我的 expr 加上括号时打错了,但是是的。但只需删除 ==True 这只是多余的,你永远不会遇到问题!

标签: python python-3.x function keyword-argument


【解决方案1】:
def examplefunc(x,y,**kwargs):

    print(kwargs['extraarg'])
    if ('extraarg' in kwargs)==True
        print(kwargs['extraarg'])
        print("This is not printed")

    if 'extraarg' in kwargs: print("This is printed")



if __name__ == "__main__":

    examplefunc(3,2,extraarg=True) 

输出:

True
True
This is not printed
This is printed

【讨论】:

  • 这不是问题
  • 好吧,代码不会检查extraarg是真还是假
  • @zabop 哦,对了。我添加了对 extraarg == True 的检查
  • 我发现在 Q 的 cmets 中建议使用 if ('extraarg' in kwargs)==True 更好,否则它可以工作,谢谢
  • 它之所以有效,是因为您没有链接运算符!这个答案没有解释你的问题,它只是提供了一个不同的解决方案。 @Jean-FrançoisFabre 在他的评论中指出了正确的方向!
猜你喜欢
  • 2021-01-20
  • 2022-01-26
  • 1970-01-01
  • 2010-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多