V2EX = way to explore
V2EX 是一个关于分享和探索的地方
Sign Up Now
For Existing Member  Sign In
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
vtoexsir
V2EX  ›  Python

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

  •  
  •   vtoexsir · Oct 12, 2016 · 2824 views
    This topic created in 3494 days ago, the information mentioned may be changed or developed.
    class C(object):
    @classmethod
    def m():
    pass


    m()是类方法,调用:
    C.m()
    但我当成属性的方式调用,像这样:
    C.m
    请问该怎么弄呢?
    请最好提供个简单的例子, 多谢!
    11 replies    2016-10-13 09:39:53 +08:00
    cheetah
        1
    cheetah  
       Oct 12, 2016
    没什么简单的办法,也许用 metaclass 可以做到
    glogo
        2
    glogo  
       Oct 12, 2016
    使用 data descriptor?或者是实现 __call__()方法这种?
    Yinz
        3
    Yinz  
       Oct 12, 2016 via iPhone
    @property
    Google 的话解释和例子会比较详细
    Yinz
        4
    Yinz  
       Oct 12, 2016 via iPhone
    咦,没看到是类方法🤔
    binux
        5
    binux  
       Oct 12, 2016
    ```
    class C(object):
    @classmethod
    def _m(cls):
    return 1

    m = property(lambda s: s._m())
    ```
    thinker3
        6
    thinker3  
       Oct 12, 2016   ❤️ 1
    类方法不是还有一个 cls 参数么?
    eric6356
        7
    eric6356  
       Oct 12, 2016   ❤️ 1
    stackoverflow 上有个方法是继承 property 并且改写__get__方法
    http://stackoverflow.com/questions/128573/using-property-on-classmethods
    aaronzjw
        8
    aaronzjw  
       Oct 12, 2016   ❤️ 1
    SlipStupig
        9
    SlipStupig  
       Oct 13, 2016
    \@property
    linuxchild
        10
    linuxchild  
       Oct 13, 2016 via iPhone
    bwangel
        11
    bwangel  
       Oct 13, 2016
    参考这篇答案: http://stackoverflow.com/questions/128573/using-property-on-classmethods

    写了一个小例子, classProperty 只有 getter 可以使用:

    <script src="https://gist.github.com/bwangel23/6323253b0f1fcb48a578c21c86af95ca.js"></script>
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3284 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 65ms · UTC 14:05 · PVG 22:05 · LAX 07:05 · JFK 10:05
    ♥ Do have faith in what you're doing.