相关疑难解决方法(0)

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

我希望将一个普通的旧函数作为类常量.但是,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"方法是什么?

python class

10
推荐指数
1
解决办法
3204
查看次数

标签 统计

class ×1

python ×1