2012-10-05 75 views
1

我有一個函數將函數作爲參數之一,但取決於函數可能是幾個函數之一的上下文(它們都是用於創建sorted方法的規則的比較函數)。有沒有什麼辦法可以檢查哪個函數被傳入函數?我在想什麼是這樣的條件邏輯:檢查函數傳遞到函數中的函數

def mainFunction (x, y, helperFunction): 
    if helperFunction == compareValues1(): 
     do stuff 
    elif helperFunction == compareValues2(): 
     do other stuff 

等會這樣嗎?我是否需要在檢查函數的所有參數時通過?有沒有更好的辦法?

+3

如果什麼用戶創建自己的功能? –

回答

3

你是在正確的軌道上,你只需要刪除這些價格調整匯率ntheses:

def mainFunction (x, y, helperFunction): 
    if helperFunction == compareValues1(): <-- this actually CALLS the function! 
     do stuff 
    elif helperFunction == compareValues2(): 
     do other stuff 

相反,你會想

def mainFunction (x, y, helperFunction): 
    if helperFunction is compareValues1: 
     do stuff 
    elif helperFunction is compareValues2: 
     do other stuff 
+0

這相對於我的驗證其實際上真正的功能而不僅僅是相同的名稱 –

+0

注意:如果您關心使用'is'關鍵字來比較函數標識,請閱讀Raymond的答案:http://stackoverflow.com /問題/ 7942346 /如何-做的Python - 比較 - 功能 – wim

0

由於功能本身在Python的對象,所以,當你傳遞一個函數給你的函數,引用複製到該參數。所以,你可以直接對它們進行比較,看它們是否相等: -

def to_pass(): 
    pass 

def func(passed_func): 
    print passed_func == to_pass # Prints True 
    print passed_func is to_pass # Prints True 

foo = func # Assign func reference to a different variable foo 
bar = func() # Assigns return value of func() to bar.. 

foo(to_pass) # will call func(to_pass) 

# So, you can just do: - 

print foo == func # Prints True 

# Or you can simply say: - 
print foo is func # Prints True 

所以,當你通過to_pass的功能func(),以to_pass參考在參數複製passed_func

2
>>> def hello_world(): 
... print "hi" 
... 
>>> def f2(f1): 
... print f1.__name__ 
... 
>>> f2(hello_world) 
hello_world 

其重要的要注意這只是檢查名稱不簽名..