1
arzon 2012-07-13 18:08:33 +08:00
貌似只有getattr了, 不知道麻烦从何而来
def __getattr__(self, name): try: return self[name] except KeyError: raise AttributeError(name) |
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 |
4
cute 2012-07-13 18:46:21 +08:00
继承UserDict
|
5
013231 OP 感謝@hwywhywl的回答. 在Python中, 類同樣也是對象. 而一個類的類是由__metaclass__定義的, 默認是type. 所以想使一個類可下標訪問, 在它的__metaclass__中實現__getitem__即可. 關於__metaclass__的詳細解釋: http://stackoverflow.com/questions/100003/what-is-a-metaclass-in-python?answertab=votes#tab-top
|