Pythonic API 设计(类似 C# 中的重写索引运算符?)

2024-05-18 05:36:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个地下城的东西,里面有房间。每个房间都有一个名字。我想设计一个类,从它的客户端接受这个API:

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

到目前为止,我能设计出这样的东西:

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

只需编写一个接受str参数并按名称查找文件室的方法就很容易了。你知道吗

但是如果我想让房间的“访问者”表现得像一本字典呢?我有什么选择?你知道吗

我想过这个,但作为一个真正的初学者,我不能决定:

  • 创建dict的子类型,重写其__getattribute__方法

我不喜欢的是,客户能够这样做:

dungeon.room.keys()

然后找出所有房间的名字。你知道吗

如果专家觉得这个问题很愚蠢。。。对不起的。我还能说什么?你知道吗


Tags: 方法name名称api客户端参数字典名字
1条回答
网友
1楼 · 发布于 2024-05-18 05:36:30

在代码中定义__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!

相关问题 更多 >