简体   繁体   English

Python布尔值作为函数中的参数

[英]Python Boolean as argument in a function

I have a function that needs input as True/False that will be fed in from another function. 我有一个需要输入为True / False的函数,它将从另一个函数输入。 I would like to know what is the best practice to do this. 我想知道这样做的最佳做法是什么。 Here is the example I am trying: 这是我正在尝试的示例:

def feedBool(self, x):

    x = a_function_assigns_values_of_x(x = x)
    if x=="val1" or x == "val2" :
      inp = True
    else
      inp = False

    feedingBool(self, inp)
    return

def feedingBool(self, inp) :
    if inp :
      do_something
    else :
      dont_do_something
    return

You can do: 你可以做:

def feedBool(self, x):
    x = a_function_assigns_values_of_x(x = x)    
    feedingBool(self, bool(x=="val1" or x == "val2"))

Or, as pointed out in the comments: 或者,正如评论中指出的那样:

def feedBool(self, x):
    x = a_function_assigns_values_of_x(x = x)    
    feedingBool(self, x in ("val1","val2"))

why not just: 为什么不呢:

inp = x in ("val1", "val2")

of cause it can be compacted even more directly in the call to the next function, but that will be at the cost of some readability, imho. 因为它可以在调用下一个函数时更直接地压缩,但这将以一些可读性为代价,即imho。

You usually put the test in a function and spell out the consequence: 您通常将测试放在一个函数中并拼出结果:

def test(x):
    # aka `return x in ("val1", "val2")` but thats another story
    if x=="val1" or x == "val2" :
      res = True
    else
      res = False    
    return res

def dostuff(inp):
    # i guess this function is supposed to do something with inp
    x = a_function_assigns_values_of_x(inp)
    if test(x):
      do_something
    else :
      dont_do_something

dostuff(inp)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM