python怎么把类方法装饰为属性?

smfsir
  • 147
class C(object):
    @classmethod
    def m():
        pass

m()是类方法,调用代码如下:

C.m()

但我想当成属性的方式调用,像这样:

C.m

请问该怎么弄呢?
请最好提供个简单的例子, 多谢!

回复
阅读 2.5k
2 个回答
✓ 已被采纳
class classproperty(object):

    def __init__(self, fget):
        self.fget = fget

    def __get__(self, owner_self, owner_cls):
        return self.fget(owner_cls)

class C(object):

    @classproperty
    def x(cls):
        return 1

assert C.x == 1
assert C().x == 1

详情参考:http://stackoverflow.com/ques...

class C(object):
    @property
    def m():
        pass
宣传栏