无法在Python中将函数用作类属性 [英] Can't have a function as a class attribute in Python

查看:83
本文介绍了无法在Python中将函数用作类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想拥有一个普通的旧函数作为类常量。但是,Python对我来说有帮助地将其变成一种方法:

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)




  • 有没有办法防止我的函数成为方法?

  • 在任何情况下,解决此问题的最佳 Pythonic方法是什么?

  • 推荐答案

    静态方法:

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

    或:

    class C(object):
        a = 17
        b = staticmethod(lambda x : x+1)
    

    这篇关于无法在Python中将函数用作类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆