在Python中不能将函数作为类属性

hug*_*omg 10 python class

我希望将一个普通的旧函数作为类常量.但是,Python"有帮助"将它变成了一种方法:

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)
Run Code Online (Sandbox Code Playgroud)
  • 有没有办法阻止我的功能成为一种方法?
  • 无论如何,对这个问题最好的"Pythonic"方法是什么?

blu*_*ume 22

静态方法:

class C(object):
    a = 17

    @staticmethod
    def b(x):
      return x+1
Run Code Online (Sandbox Code Playgroud)

要么:

class C(object):
    a = 17
    b = staticmethod(lambda x : x+1)
Run Code Online (Sandbox Code Playgroud)