1

我正在尝试在 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)

我怎样才能让它工作?

4

2 回答 2

0

做作业apply(A)。但是,您还需要解决问题func

于 2017-07-19T13:51:57.553 回答
0

所以在这里你有很多问题。我不确定您要达到什么目标,但是您肯定必须再看一下文档。首先,看看你的班级。在里面你要指定一个函数,而 Pythondef func(args)对它使用了一个方法。如果你想在一个类中使用它,你应该使用它self作为参数。

从文档中:

class MyClass:
    """A simple example class"""
    i = 12345

    def f(self):
        return 'hello world'

此外,lambda, in words 是一个匿名函数。定义它时,您应该执行以下操作:

s = lambda x: x**2
s(2)

并且x将是您的函数参数,以及x**2您想要返回的内容,因此该函数将返回 4。

希望它会减少一些混乱,你会以更好的方式编写你的代码。祝你好运!

于 2017-07-19T13:55:30.693 回答