0

我有一个需要输入为 True/False 的函数,该函数将从另一个函数中输入。我想知道这样做的最佳做法是什么。这是我正在尝试的示例:

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
4

3 回答 3

1

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"))
于 2013-05-29T19:43:15.830 回答
1

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.

于 2013-05-29T19:45:36.670 回答
0

您通常将测试放在一个函数中并说明结果:

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)
于 2013-05-29T19:48:45.127 回答