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

纵然是瞬间 提交于 2020-01-10 03:45:08

问题


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?

回答1:


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)



回答2:


Use staticmethod:

class C(object):
    a = 17
    @staticmethod
    def b(x):
        return x + 1



回答3:


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


来源:https://stackoverflow.com/questions/5999575/cant-have-a-function-as-a-class-attribute-in-python

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!