python-3.x 函数调用作为参数

cqoc49vn  于 8个月前  发布在  Python
关注(0)|答案(1)|浏览(89)
def zero():
    return 0

def one():
    return 1

def func(x):
    return 0

func(zero(one()))

字符串
我想在func()中执行一个任务,该任务基于哪个函数被称为x
因此,在上面给出的代码中,是否可能知道哪个函数被调用作为func()的参数,即one()zero()
并且函数调用可能会或可能不会在one()处停止,它可能会像func(zero(one(two())))一样继续

1szpjjfi

1szpjjfi1#

由于zero()one()返回的值不同,您可以这样做:

def zero():
    return 0

def one():
    return 1

def func(x):
    if x == 0:
        print('zero() called')
    elif x == 1:
        print('one() called')

func(zero())

字符串
由于在调用func(zero())时只传递zero()的返回值,因此不可能在func()中获取函数的名称。
如果你想要函数的确切名称,在func()中,你可以传递函数对象,并使用__name__属性访问它的名称。你也可以在func()中调用x()传递的函数:

def zero():
    print('0')
    return 0

def one():
    print('1')
    return 1

def func(x):
    x() # Call the function which was passed
    if x == zero:
        print('zero() called')
    elif x == one:
        print('one() called')

func(zero) # Note the lack of '()' after zero

相关问题