I want to have a plain old function as a class constant. However, Python "helpfully" turns it into a method for me:
class C(object):
a = 17
b = (lambda x : x+1)
print C.a # Works fine for int attributes
print C.b # Uh-oh... is a <unbound method C.<lambda>> now
print C.b(1) # TypeError: unbound method <lambda>() must be called
# with C instance as first argument (got int instance instead)
- Is there a way to prevent my function from becoming a method?
- In any case, what is the best "Pythonic" approach to this problem?
Use
staticmethod
:staticmethod:
Or:
Define your function in a module but not class. It's better in your case.
First paramter of normal python method is
self
,self
must be an instance object.you should use staticmethod:
or add
self
parameter, and make an instance of C:another choice is using classmethod (just show you can do this):