看这段代码:
class MyClass_1():
@staticmethod
def method_1(func):
return func(1, 2, 3)
class MyClass_2():
my_func = lambda a,b,c : a*b*c # I need to call this method
def method_2(self):
result = MyClass_1.method_1(self.my_func)
print(result)
我的错误:
类型错误: () 需要 3 个位置参数,但给出了 4
个
我需要以与上述代码相同的方式调用 lambda 函数my_func
,但一个self
从我不知道的地方出现并导致此错误。
我错过了什么?
由于 my_func
是 MyClass_2
的类属性,因此您不应该通过 self
(类的实例)访问它。 相反,您应该直接通过类访问它:
result = MyClass_1.method_1(MyClass_2.my_func)
^^^^^^^^^
演示:
>>> class MyClass_1():
... @staticmethod
... def method_1(func):
... return func(1, 2, 3)
...
>>> class MyClass_2():
... my_func = lambda a,b,c : a*b*c # I need to call this method
... def method_2(self):
... result = MyClass_1.method_1(MyClass_2.my_func)
... print(result)
...
>>> MyClass_2().method_2()
6
>>>
有关更多信息,您可以查看以下来源:
- https://docs.python.org/3/reference/compound_stmts.html#class-definitions
- Python:类和实例属性之间的区别
lambda
只是定义函数对象的不同语法。类体中的函数始终绑定并传递self
参数(因为它们是描述符)。
只需给出你lambda
这个论点:
my_func = lambda self, a, b, c: a * b * c
另一种方法是解开方法并传入普通函数对象:
result = MyClass_1.method_1(self.my_func.__func__)
或者将lambda
包装在staticmethod
对象中:
my_func = staticmethod(lambda a, b, c: a * b * c)
你需要给你的lambda
一个自我论证。 Lambda 只是普通函数。 这两者之间没有区别:
class Foo():
my_func = lambda a,b,c : a*b*c
而这个
class Foo():
def my_func(a, b, c):
return a*b*c
在这两种情况下,my_func
都是方法,如果在实例上调用该方法,则会传递self
方法。
lambda是小型匿名函数,可以直接写入方法的参数列表中。通常不希望将它们分配给变量。这里lambda的典型用法是:
class MyClass_1():
@staticmethod
def method_1(func):
return func(1, 2, 3)
class MyClass_2():
def method_2(self):
result = MyClass_1.method_1(lambda a,b,c: a*b*c)
print(result)
MyClass_2().method_2()