1

I try create map like object which contains lambda functions:

class Map(object):
    a = lambda x: True

But python assumes a as Map class method and expects what it accept self argument which is Map instance.

Of course I can write

class Map(object):
    @staticmethod
    def a(x):
       return True

But it is too long. Is it possible to make the first class?

3
  • 6
    Is "too long" really an issue worth worrying about? Commented Jan 29, 2014 at 14:03
  • Why do you want this to be a class, not just a module of functions? Commented Jan 29, 2014 at 14:11
  • 1
    Note that while we use the phrase as shorthand sometimes, there's not really a lambda function. It's just a different syntax for creating certain limited kinds of perfectly normal functions, usually for convenience when a function only needs to exist as an argument to another function. If you're immediately giving it a name, there's not much reason to use a lambda. Commented Jan 29, 2014 at 14:11

2 Answers 2

4

Yes, just apply the @staticmethod decorator manually to the lambda:

class Map(object):
    a = staticmethod(lambda x: True)

or simply give your lambda that required self argument:

class Map(object):
    a = lambda self, x: True
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, but I keep in mind maybe there is way without using decorator.
@Eugene: In Python 3, if you don't create an instance of Map(), Map.a('something') will work without requiring a self argument. But why bother with a class then at all?
@Eugene: If you are creating an instance, these two choices are it, really. You could write your own descriptor object to wrap the lambda, but that'd be enormous overkill for no gain.
0

It's very unclear what you are asking. The first piece of code correctly does what it is supposed to do -- it sets that function as attribute a of Map.

Map.a(42)

But python assumes a as Map class method

Python doesn't "assume" it is a "class method". It is not a "class method". All variables set in the body of a class declaration become members of the class. What were you expecting?

"Class method" refers to things with the @classmethod decorator. This is different from things with the @staticmethod decorator, and also different from things without either. As is, it is neither a "class method" nor a "static method". You need to understand the differences among all three.

The @staticmethod decorator only affects when you try to call a method on an instance of Map. You did not say you were doing any such thing. When accessing an attribute of class directly and calling it, there is no difference.

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.