Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't have a function as a class attribute in Python

Tags:

python

class

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?
like image 659
hugomg Avatar asked May 14 '11 03:05

hugomg


2 Answers

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)
like image 138
bluepnume Avatar answered Oct 20 '22 16:10

bluepnume


Use staticmethod:

class C(object):
    a = 17
    @staticmethod
    def b(x):
        return x + 1
like image 44
senderle Avatar answered Oct 20 '22 14:10

senderle