检查传递给函数的函数

2024-03-29 12:22:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个函数,它接受一个函数作为它的参数之一,但是根据上下文,这个函数可以是几个函数中的一个(它们都是用于为sorted方法创建规则的比较函数)。有没有办法检查哪个函数被传递到了一个函数中?我想的是这样的条件逻辑:

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

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


Tags: 方法函数参数if规则defdosorted
3条回答
helperFunction==compareValues1
>>> def hello_world():
...    print "hi"
...
>>> def f2(f1):
...    print f1.__name__
...
>>> f2(hello_world)
hello_world

重要的是要注意这只检查名字而不是签名。。你知道吗

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

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

相关问题 更多 >