Lambda函数传递不需要的自我 [英] Lambda function passing not desired self
本文介绍了Lambda函数传递不需要的自我的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
查看以下代码:
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)
我的错误:
TypeError:()接受3个位置参数,但给出了4个
TypeError: () takes 3 positional arguments but 4 were given
我需要以与上面的代码相同的方式调用lambda函数my_func
,但是在我不知道的地方出现self
并导致此错误.
I need to call the lambda function my_func
in the same way as the code above, but a self
is appearing from somewhere I don't know and causing this error.
我想念什么?
推荐答案
由于my_func
是MyClass_2
的类属性,因此您不应该通过self
(该类的实例)访问它.相反,您应该直接通过类访问它:
Since my_func
is a class attribute of MyClass_2
, you should not be accessing it through self
(an instance of the class). Instead, you should be accessing it through the class directly:
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
>>>
有关更多信息,您可以查看以下来源:
For more information, you can check out these sources:
- https://docs.python.org/3/reference/compound_stmts.html#class-definitions
- Python: Difference between class and instance attributes
这篇关于Lambda函数传递不需要的自我的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文