10

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?
Alex Povel
  • 150
  • 2
  • 12
hugomg
  • 68,213
  • 24
  • 160
  • 246
  • Note, the above code works fine in Python 3, where the concept of unbound methods is gone: https://www.python.org/download/releases/3.0/whatsnew/ . `C.b` is simply a `function`, usable as such in the usual manner. – Alex Povel Jun 10 '22 at 13:38

3 Answers3

23

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)
bluepnume
  • 16,460
  • 8
  • 38
  • 48
4

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:

class C(object):
    a = 17
    b = staticmethod(lambda x: x+1)
print C.b(1)
# output: 2

or add self parameter, and make an instance of C:

class C(object):
    a = 17
    b = lambda self, x: x+1
c = C()
c.b(1)
# output: 2

another choice is using classmethod (just show you can do this):

class C(object):
    a = 17
    b = classmethod(lambda cls, x: x+1)
C.b(1)
# output: 2
user142800
  • 41
  • 3
4

Use staticmethod:

class C(object):
    a = 17
    @staticmethod
    def b(x):
        return x + 1
senderle
  • 145,869
  • 36
  • 209
  • 233
  • But you should consider [these caveats](http://stackoverflow.com/questions/5212071/python-class-design-staticmethod-vs-method/5212190#5212190). – senderle May 14 '11 at 03:25