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)
staticmethod:
class C(object):
a = 17
@staticmethod
def b(x):
return x+1
Or:
class C(object):
a = 17
b = staticmethod(lambda x : x+1)
Use staticmethod
:
class C(object):
a = 17
@staticmethod
def b(x):
return x + 1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With