2013-05-29 69 views
0

我有一個函數,需要輸入作爲True/False,將從另一個函數提供。我想知道做這件事的最佳做法是什麼。這是我想的例子:作爲函數中的參數Python布爾作爲

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 

回答

1

你可以這樣做:

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

或者,正如在評論中指出:

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

你不應該需要'bool'有 – Andbdrew

+0

無需轉換爲'bool' – jamylak

+0

我只是擺明... – dawg

1

爲什麼不乾脆:

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

因爲它可以壓縮更直接在下一個函數的調用中,但這將以一些可讀性爲代價,即imho。

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)