Ankur Agarwal
Ankur Agarwal

Reputation: 24768

Defining a @classmethod lambda in python

class TestClass(object):
    aa = lambda x: 35
    def __init__(self):
        self.k = self.aa()


o = TestClass()
print o.k

This gives me 35, which I understand why.

But this:

class TestClass(object):
    @classmethod
    aa = lambda x: 35
    print type(aa)
    def __init__(self):
        self.k = TestClass.aa()


o = TestClass()
print o.k

This gives me

  File "test1.py", line 3
    aa = lambda x: 35
     ^
SyntaxError: invalid syntax

Why so ?

Upvotes: 1

Views: 332

Answers (2)

LVFToENlCx
LVFToENlCx

Reputation: 875

You can't use a decorator on a lambda. You could replace it with

aa = classmethod(lambda x:35)

Upvotes: 1

BrenBarn
BrenBarn

Reputation: 251488

Decorators are only syntactically valid on def and class statements. But the decorator syntax is just shorthand for calling the decorator with the decorated function (or class) as its argument, so you can achieve the same result with:

class TestClass(object):
    aa = classmethod(lambda x: 35)
    # etc.

Upvotes: 6

Related Questions