具有“enumlike”类的未绑定方法

2024-09-28 22:23:42 发布

您现在位置:Python中文网/ 问答频道 /正文

考虑以下代码:

ff = lambda x : x
gg = lambda x : x*2
class FunctionCollection(object):
    f = ff
    g = gg

def FunctionCaller(x, Type = FunctionCollection.f):
    return Type(x)

y = FunctionCaller(x)

它返回一个

unbound method () must be called with FunctionCollection instance as first argument (got ndarray instance instead)

我不明白的信息。 一个显而易见的解决方案是在FunctionCollection中定义ff和gg,但是我想知道是否不能在模块中定义ff和gg,然后创建一个包含指向这些函数的“指针”的枚举,最后将这些“指针”作为参数传递。抱歉给你起了个C风格的名字。你知道吗

怎么了?你知道吗

谢谢你

迈克


Tags: instancelambda代码return定义objectdeftype
1条回答
网友
1楼 · 发布于 2024-09-28 22:23:42

您的代码实际上在python3.x上工作。如果您需要支持python2.x,可以使用staticmethod:

ff = lambda x : x
gg = lambda x : x*2
class FunctionCollection(object):
    f = staticmethod(ff)
    g = staticmethod(gg)

def FunctionCaller(x, Type = FunctionCollection.f):
    return Type(x)

y = FunctionCaller(1.0)
print(y)

另一种选择是使用FunctionCollection作为“单例”,并将函数绑定到单个实例。。。你知道吗

ff = lambda x : x
gg = lambda x : x*2
class FunctionCollection(object):
    pass

FUNC_COLLECTION = FunctionCollection()
FUNC_COLLECTION.f = ff
FUNC_COLLECTION.g = gg


def FunctionCaller(x, Type = FUNC_COLLECTION.f):
    return Type(x)

y = FunctionCaller(1.0)
print(y)

I would like to know if it is not possible to define ff and gg in a module, then create an enum containing the "pointers" to those function, and finally pass those "pointers" as arguments.

我认为这是一个显而易见的问题。。。为什么你需要这种额外的间接层次?对我来说似乎没有必要。你知道吗

当然,这并不是说没有必要,只是因为我还不明白目的……

相关问题 更多 >