开发者

Python: subscriptable class

My class Item describes certain items, which are naturally known by their numeric ID (0, 1, 2, ...). I have implemented a registry inside the class, which indexes all the objects by their ID. I also have a method that retrieves an object by its ID:

class Item
    _registry = []
    def __init__(self):
        self._registry.appe开发者_开发技巧nd(self)
        # ...
    @classmethod
    def get_item_by_id(cls, k):
        return cls._registry[k]
    # ...

Is this a reasonable design?

Assuming it is, would it be ok to allow subscripts for the Item class itself? I can (I think) define __getitem__ in Item's metaclass, thus allowing the syntax Item[2] instead of Item.get_item_by_id(2).

If it has any problems (e.g., too weird, can cause undesirable side effects, etc), please let me know.


Nope. That's perfectly fine. It's definitely better than the long form. Just make sure you return sensible exceptions (a KeyError with a descriptive message, e.g. Invalid id for element) when someone uses an incorrect index. Also, make sure that you document this behavior, otherwise there'd be no point in making the object subscriptable in the first place.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜