gpt4 book ai didi

python - 分配函数,忽略第一个值

转载 作者:行者123 更新时间:2023-11-28 21:54:27 25 4
gpt4 key购买 nike

首先让我说我不认为它是重复的。我检查了 Ignore python multiple return value已经。这不是我需要的。

所以,我有一个函数 f:

def f(parameters):
return a,b # returns two values

module1.py 中定义。现在,我想让另一个类知道这个函数,所以我这样做:

import module1

Class MyClass:

def __init__(self):
self.function = module1.f

当然,这发生在 module2.py 中。我需要在另一个模块中调用它,module3.py 像这样:

import module2

instance = module2.MyClass()

otherFunction(args, instance.function )

关键在于:otherFunction 的第二个参数必须是一个返回单个值的函数(目前它返回两个值)。我试过了

import module1

Class MyClass:

def __init__(self):
self.function = module1.f[0]

但这行不通。有任何想法吗?我无法更改 module3.py。我可以更改其他人,但随后我将不得不对我的项目进行大量更改,这似乎非常痛苦。我使用 python 2.6。不过,如果您找到的任何解决方案也适用于 python3,我会很高兴。

最佳答案

如果您需要接受任意函数,那么您可以使用 lambda 或包装函数:

self.function = lambda *args: module1.f(*args)[0]

否则,请查看@Christian 的回答。

关于python - 分配函数,忽略第一个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24235405/

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