1
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 ?

2 Answers 2

6

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.
Sign up to request clarification or add additional context in comments.

Comments

1

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

aa = classmethod(lambda x:35)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.