gpt4 book ai didi

python - VBA如何使用部分参数调用另一个函数内的函数

转载 作者:行者123 更新时间:2023-12-01 07:29:05 25 4
gpt4 key购买 nike

所以我想将以下Python代码翻译成VBA(只是为了说明问题的玩具示例,详细信息省略)。

def numerical_integration(fun, a, b):
"""

:param fun: callable
:param a, b: float
:return: float
"""
# do something based on both fun and a, b
res = ...
return res


def h(x, k):
"""
helper func
:param x: float, main arg
:param k: float, side param
:return: float
"""
# calc based on both x and k
res = ...
return res


def main_function(k):
"""

:param k: float
:return: float
"""
a, b = 0.0, 1.0
res = numerical_integration(fun=lambda x: h(x, k), a=a, b=b)
return res

问题是我不知道如何在 VBA 中正确传递“部分”函数作为参数。我发现如何在 VBA 中传递“整个”函数 this post 。这个想法是将函数作为字符串传递,然后让 VBA 计算该字符串(我猜类似于 Python eval 等价物?)。但我不知道如果我的函数是部分的,即我希望它仅在第一个参数上成为一个函数,例如 lambda x: f(x, k) ,其中第二个参数位于主函数的上下文中。

感谢您提前提出任何建议。

最佳答案

我不了解Python和“部分”函数,但我尝试使用对象来替换它。我创建了一个类模块,试图模仿“部分”函数,具有可选参数和默认值。

Public defaultX As Double
Public defaultY As Double

Public Function h(Optional x As Variant, Optional y As Variant) As Double

' The IsMissing() function below only works with the Variant datatype.

If (IsMissing(x)) Then
x = defaultX
End If
If (IsMissing(y)) Then
y = defaultY
End If

h = x + y

End Function

然后我决定在 numeric_integration 中使用“CallByName”函数。这是主模块代码:

Public Function numerical_integration(fun As clsWhatEver, funName As String, a As Double, b As Double) As Integer

Dim r1 As Double, r2 As Double

' CallByName on the "fun" object, calling the "funName" function.
' Right after "vbMethod", the parameter is left empty
' (assuming default value for it was already set).
r1 = CallByName(fun, funName, VbMethod, , a)
r2 = CallByName(fun, funName, VbMethod, , b)

numerical_integration = r1 + r2

End Function

Public Function main_function(k As Double) As Double
Dim res As Double

Dim a As Double, b As Double
a = 0#
b = 1#

Dim oWE As New clsWhatEver
' Sets the default value for the first parameter of the "h" function.
oWE.defaultX = k

res = numerical_integration(oWE, "h", a, b)

main_function = res

End Function

关于python - VBA如何使用部分参数调用另一个函数内的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57301376/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com