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

2012-07-13 17:51:23 +08:00
 013231
想讓一個對象可下標訪問很簡單, 只要在它的類定義中實現__ getitem__就可以了.
可是我想讓一個類可以下標訪問, 應該怎麼做呢?
具體來說是要達到這個效果:
http://gist.github.com/3103973
我知道getattr有同樣地作用, 但它既麻煩又不優雅.
4268 次点击
所在节点    Python
5 条回复
arzon
2012-07-13 18:08:33 +08:00
貌似只有getattr了, 不知道麻烦从何而来
def __getattr__(self, name):
try:
return self[name]
except KeyError:
raise AttributeError(name)
013231
2012-07-13 18:33:40 +08:00
@arzon 你確定是在回答我的問題嗎?
hwywhywl
2012-07-13 18:45:50 +08:00
class TableMeta(type):
def __getitem__(cls, name):
return getattr(cls, name, None)

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

__metaclass__ = TableMeta
cute
2012-07-13 18:46:21 +08:00
继承UserDict
013231
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/42302

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX