V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
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 · 2012-07-13 17:51:23 +08:00 · 4232 次点击
    这是一个创建于 4276 天前的主题,其中的信息可能已经有所发展或是发生改变。
    想讓一個對象可下標訪問很簡單, 只要在它的類定義中實現__ getitem__就可以了.
    可是我想讓一個類可以下標訪問, 應該怎麼做呢?
    具體來說是要達到這個效果:

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

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

    __metaclass__ = TableMeta
    cute
        4
    cute  
       2012-07-13 18:46:21 +08:00
    继承UserDict
    013231
        5
    013231  
    OP
       2012-07-14 01:03:22 +08:00
    感謝@hwywhywl的回答. 在Python中, 類同樣也是對象. 而一個類的類是由__metaclass__定義的, 默認是type. 所以想使一個類可下標訪問, 在它的__metaclass__中實現__getitem__即可. 關於__metaclass__的詳細解釋: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python?answertab=votes#tab-top
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3561 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 04:59 · PVG 12:59 · LAX 21:59 · JFK 00:59
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.