Pythonic API设计(C#类覆盖索引运算符?)

时间:2013-02-23 23:35:14

标签: python

我有一个包含房间的Dungeon对象​​。每个房间都有一个名字。我想设计一个从客户端接受此API的类:

dungeon = Dungeon()
room = dungeon.room['room_name']

到目前为止,我能够设计出类似的东西:

dungeon = Dungeon()
room = dungeon.room('room_name')

很容易编写一个采用str参数并按名称查找房间的方法。

但是,如果我希望房间“访问者”表现得像字典呢?我有什么选择?

我已经想过这个,但作为一个真正的初学者,我无法决定:

  • 创建dict的子类型,覆盖其__getattribute__方法

我不喜欢的是客户能够做到这一点:

dungeon.room.keys()

并发现所有房间名称。

如果问题对专家来说听起来很愚蠢......抱歉。我还能说什么呢?

1 个答案:

答案 0 :(得分:4)

在代码中定义__getitem____(self, key) - 这使您可以对对象进行字典式访问。

class Room(object):
    # stuff...
    def __getitem__(self, key):
        # get room using the key and return the value
        # you should raise a KeyError if the value is not found
        return self.get_room(key)

dungeon.room = Room()
dungeon.room['room_name']  # this will work!