Skip to main content
 首页 » 编程设计

python之检查传递给函数的函数

2025年05月04日18davidwang456

我有一个将函数作为其参数之一的函数,但根据上下文,该函数可能是几个函数之一(它们都是比较器函数,用于为 sorted 方法创建规则) .有没有办法检查哪个函数被传递给函数?我在想的是像这样的某种条件逻辑:

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

等这行得通吗?在检查函数是否存在时,是否需要传入该函数的所有参数?有没有更好的办法?

请您参考如下方法:

你走在正确的轨道上,你只需要删除那些括号:

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