Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/334.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Python中,如何用变量替换函数调用的一部分?_Python - Fatal编程技术网

在Python中,如何用变量替换函数调用的一部分?

在Python中,如何用变量替换函数调用的一部分?,python,Python,我有一本字典,里面有一些函数表达式作为值。除了中间部分,每个值非常相似。在下面的示例中,在长公式中只有earn\u yld、free\u cash\u flow\u yield和eps\u growth不同 factor_bql = { "ltm_earnings_yield": bq.func.dropna(bq.data.earn_yld(as_of_date=bq.func.RANGE(params['start'],params['end']))), "ltm_fcf_y

我有一本字典,里面有一些函数表达式作为值。除了中间部分,每个值非常相似。在下面的示例中,在长公式中只有
earn\u yld
free\u cash\u flow\u yield
eps\u growth
不同

factor_bql = {
    "ltm_earnings_yield": bq.func.dropna(bq.data.earn_yld(as_of_date=bq.func.RANGE(params['start'],params['end']))),
    "ltm_fcf_yield": bq.func.dropna(bq.data.free_cash_flow_yield(as_of_date=bq.func.RANGE(params['start'],params['end']))),
    'ltm_eps_growth': bq.func.dropna(bq.data.eps_growth(as_of_date=bq.func.RANGE(params['start'],params['end'])))
}
有没有办法写一个函数或变量来简化字典中的值

def simple_formula(xyz):
    ... ...

factor_bql = {
    "ltm_earnings_yield": simple_formula('earn_yld'),
    "ltm_fcf_yield": simple_formula('free_cash_flow_yield'),
    'ltm_eps_growth': simple_formula('eps_growth')
}

假设bq.data是某个对象:

def simple_formula(xyz):
    method = getattr(bq.data, xyx) # get a method by its name
    return bq.func.dropna(method(as_of_date=bq.func.RANGE(params['start'],params['end'])))

我会用以下方法来做:

def简单_公式(fn):
返回bq.func.dropna(fn(as_of_date=bq.func.RANGE(params['start'],params['end']))
系数_bql={
“ltm收益率”:简单的公式(bq.data.earn.yld),
“ltm\u fcf\u收益率”:简单的公式(bq.数据、自由现金流\u收益率),
“ltm\u每股收益增长”:简单的公式(bq.data.eps\u增长)
}

因此,函数本身(不是它们的名称)是
simple\u formula

的参数。您可以使用
globals
函数通过其名称的字符串表示来调用当前模块中的函数

def func1(条形):
返回“func1”+str(条形)
def func2(巴):
返回“func2”+str(条形)
def简单公式(函数名称):
返回globals()[func_name](bar=“baz”)
系数_bql={
“key1”:简单_公式(“func1”),
“key2”:简单公式(“func2”),
}
打印(factor_bql[“key2”])#打印“func2baz”

谢谢。我尝试了这种方法并得到了以下错误消息:“文件”,第20行返回bq.func.dropna(方法((as_of_date=bq.func.RANGE(params['start'],params['end']))^SyntaxError:无效语法“``看起来公式中的等号在生成语法错误。如果我直接使用公式,而不是简单的公式函数,这不是问题所在。看起来括号不匹配。@Tupteq--我想参数xyz在simpe_公式中是多余的?@DarrylG I假设
xyz
表示一个示例参数(如所讨论的)。但我认为您是对的,我将删除它。