pythonicapi设计(类似C#重写索引操作符?)
我有一个包含房间的地牢对象。每个房间都有一个名字。我想设计一个从客户端接受此API的类:pythonicapi设计(类似C#重写索引操作符?),python,Python,我有一个包含房间的地牢对象。每个房间都有一个名字。我想设计一个从客户端接受此API的类: dungeon = Dungeon() room = dungeon.room['room_name'] 到目前为止,我能够设计出这样的东西: dungeon = Dungeon() room = dungeon.room('room_name') 只需编写一个接受str参数并按名称查找房间的方法就很容易了 但是如果我想让房间的“访问器”表现得像一本字典呢?我有什么选择 我曾想过这一点,但作为一名真正的
dungeon = Dungeon()
room = dungeon.room['room_name']
到目前为止,我能够设计出这样的东西:
dungeon = Dungeon()
room = dungeon.room('room_name')
只需编写一个接受str参数并按名称查找房间的方法就很容易了
但是如果我想让房间的“访问器”表现得像一本字典呢?我有什么选择
我曾想过这一点,但作为一名真正的初学者,我无法决定:
- 创建dict的子类型,覆盖其
方法\uuu getattribute\uuu
dungeon.room.keys()
不过,还是要找出所有房间的名字
如果专家觉得这个问题很傻。。。很抱歉我还能说些什么?在代码中定义\uuuu getitem\uuuuuuuuuuu(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!
在代码中定义\uuuuu getitem\uuuuuuuu(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!
使用.Ref不需要子类
dict
。如果房间名称是有效的Python标识符,就像代码中显示的那样,您可以在C#前面一步,定义一个getattr,从dict中获取房间名称。然后您就可以作为dungeon.room.room_name
访问房间,实际房间仍然存储在一个内部dict中。您不必使用dict
子类来使用.Ref。如果房间名称是有效的Python标识符,就像代码中显示的那样,您可以比C#早一步,定义一个getattr,从dict中获取房间名称。然后您可以作为dungeon.room.room_name
访问房间,实际房间仍然存储在内部dict中。小挑剔:技术上,您只是定义了\uu getitem\uu
,并没有真正覆盖它。但是+1表示正确答案和代码示例。编辑答案以确保准确性。:)小挑剔:从技术上讲,您只是定义了\uu getitem\uuuu
,并没有真正覆盖它。但是+1表示正确答案和代码示例。编辑答案以确保准确性。:)