推荐学习书目
› 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
013231
V2EX  ›  Python

Python中有辦法實現可下標訪問(subscriptable)的類嗎?

  •  
  •   013231 · Jul 13, 2012 · 5775 views
    This topic created in 5226 days ago, the information mentioned may be changed or developed.
    想讓一個對象可下標訪問很簡單, 只要在它的類定義中實現__ getitem__就可以了.
    可是我想讓一個類可以下標訪問, 應該怎麼做呢?
    具體來說是要達到這個效果:

    我知道getattr有同樣地作用, 但它既麻煩又不優雅.
    5 replies  •  1970-01-01 08:00:00 +08:00
    arzon
    arzon
    Jul 13, 2012
    1
    貌似只有getattr了, 不知道麻烦从何而来
    def __getattr__(self, name):
    try:
    return self[name]
    except KeyError:
    raise AttributeError(name)
    013231
    013231
    OP
    Jul 13, 2012
    2
    @arzon 你確定是在回答我的問題嗎?
    hwywhywl
    hwywhywl
    Jul 13, 2012❤️1
    3
    class TableMeta(type):
    def __getitem__(cls, name):
    return getattr(cls, name, None)

    class Fruit(object):
    Apple = 0
    Pear = 1
    Banana = 2

    __metaclass__ = TableMeta
    cute
    cute
    Jul 13, 2012
    4
    继承UserDict
    013231
    013231
    OP
    Jul 14, 2012
    5
    感謝@hwywhywl的回答. 在Python中, 類同樣也是對象. 而一個類的類是由__metaclass__定義的, 默認是type. 所以想使一個類可下標訪問, 在它的__metaclass__中實現__getitem__即可. 關於__metaclass__的詳細解釋: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python?answertab=votes#tab-top
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1559 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 30ms · UTC 23:28 · PVG 07:28 · LAX 15:28 · JFK 18:28
    ♥ Do have faith in what you're doing.