简体   繁体   English

function 作为可选参数 python

[英]function as an optional parameter python

i am trying to write a function to check if a parameter was passed to it (which is a function ) if so call that function with an argument else if there wasn't any argument given return a value so my approach was like this:我正在尝试编写一个 function 来检查是否将参数传递给它(这是一个 function )如果这样调用 function 的话,我的任何方法都有返回值

def nine(fanc=None):
    if(fanc!=None): return fanc(9,fanc) 
    return 9

but this code rise an error which is:但是这段代码会引发一个错误,即:

TypeError: 'int' object is not callable

i know that this approach isn't correct but i couldn't find any other way to do so i have also tried using *args this way but end up with the same results:我知道这种方法不正确,但我找不到任何其他方法,所以我也尝试过以这种方式使用*args但最终得到相同的结果:

def nine(*args):
    if(len(args)!=0): return args[0](9,args) 
    return 9

I try to guess what you want but this snippet might help you:我试着猜测你想要什么,但这个片段可能会帮助你:

def fct(**kwargs):
    if 'func' in kwargs:
        f = kwargs['func']
        return f(9)
    else:
        return 9

def f(x):
    return x**2
    
print(fct())  # result = 9
print(fct(func=f))  # result = 81

You might use callable built-in function, consider following example您可以使用callable的内置 function,请考虑以下示例

def investigate(f=None):
    if callable(f):
        return "I got callable" 
    return "I got something else"
print(investigate())
print(investigate(min))

output: output:

I got something else
I got callable

Beware that callable is more broad term that function, as it also encompass objects which have __call__ method.请注意,可调用是比 function 更广泛的术语,因为它还包含具有__call__方法的对象。

If you want to check whether the passed argument is a function and, if yes, then execute it with fixed arguments, you could try the following:如果要检查传递的参数是否为 function,如果是,则使用固定的 arguments 执行它,您可以尝试以下操作:

from typing import Union
from types import FunctionType

def nine(func: Union[FunctionType, None] = None):
    if type(func) is FunctionType:
        return func(9) 
    return 9

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM