我想为一类的所有实例提供一些lambda函数。因此,我的想法是将lambda函数声明为类属性。在下面的简单代码中,为什么不能评估f定义为class属性的以下lambda函数?
In [1]: class MyClass():
...: f = lambda x : 2 * x + 1
...: def __init__(self):
...: pass
In [2]: Inst = MyClass()
In [3]: MyClass.f
Out[3]: <unbound method MyClass.<lambda>>
In [4]: MyClass.f(2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-4-5fc154bfb75c> in <module>()
----> 1 MyClass.f(2)
TypeError: unbound method <lambda>() must be called with MyClass instance as first argument (got int instance instead)
In [5]: Inst.f(3)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-5-90cde1a87da4> in <module>()
----> 1 Inst.f(3)
TypeError: <lambda>() takes exactly 1 argument (2 given)
Run Code Online (Sandbox Code Playgroud)
就像您编写了以下内容一样:
class MyClass():
def f(x):
return 2 * x + 1
def __init__(self):
pass
Run Code Online (Sandbox Code Playgroud)
第一个参数是self按约定命名的,因此即使您未命名self,函数也是一个实例方法,其第一个参数是的当前实例MyClass。
您需要使函数成为静态方法:
In [1]: %paste
class MyClass():
f = staticmethod(lambda x: 2 * x + 1)
def __init__(self):
pass
## -- End pasted text --
In [2]: MyClass.f(2)
Out[2]: 5
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2548 次 |
| 最近记录: |