Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a lambda function be a class attribute? [duplicate]

I would like to have some lambda functions available to all instances of one class. Therefore, my idea was to declare the lambda function as class attribute. In the following simplistic code, why can't I evaluate the following lambda function f that I have defined as a class attribute?

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)
like image 289
MarcoMag Avatar asked Mar 03 '17 16:03

MarcoMag


1 Answers

It's as if you wrote the following:

class MyClass():
    def f(x):
        return 2 * x + 1

    def __init__(self):
        pass

The first parameter is named self by convention, so even if you didn't name it self, your function is an instance method whose first parameter is the current instance of MyClass.

You need to make your function a static method instead:

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
like image 142
Blender Avatar answered Sep 22 '22 23:09

Blender