【发布时间】:2017-12-24 20:07:21
【问题描述】:
我正在尝试在 python 中使用此代码:
class A:
func = lambda: "go away"
@classmethod
def apply(cls):
cls.func()
A.apply()
我收到此错误:
unbound method <lambda>() must be called with A instance as first argument (got nothing instead)
我怎样才能让它工作?
【问题讨论】:
-
这是一个类方法 - 它需要是
func = lambda cls: ...... -
您不能在 Python 2.x 中将 lambda 声明为类/静态函数。你的代码应该可以在 Python 3.x 中运行,这让每个看到它的人都感到恐惧。一开始你为什么要这样做?
-
在我的原始代码中,“离开”是服务功能,在其他地方定义。 apply 函数是一个工厂方法,它使用这个函数。 func 是从外部定义的。
-
使用
func = lambda cls: ...没有帮助。它仍然失败。
标签: python python-2.x class-attributes