Reputation: 598
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?
Upvotes: 1
Views: 268
Reputation: 122449
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.
Upvotes: 0
Reputation: 1122252
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
Upvotes: 4