简体   繁体   English

在Python中实现类似列表的索引访问

[英]Implement list-like index access in Python

I'd like to be able to access some values of a python object using array-like syntax, ie: 我希望能够使用类似数组的语法访问python对象的某些值,即:

obj = MyClass()
zeroth = obj[0]
first = obj[1]

Is this possible? 这可能吗? If so, how do you implement this in the python class in question? 如果是这样,你如何在python类中实现这个?

You need to write or override __getitem__ , __setitem__ , and __delitem__ . 您需要编写或覆盖__getitem____setitem____delitem__

So for example: 例如:

class MetaContainer():
    def __delitem__(self, key):
        self.__delattr__(key)
    def __getitem__(self, key):
        return self.__getattribute__(key)
    def __setitem__(self, key, value):
        self.__setattr__(key, value)

This is a very simple class that allows indexed access to its attributes. 这是一个非常简单的类,允许对其属性进行索引访问。

Use the __getitem__ and __setitem__ methods. 使用__getitem____setitem__方法。

class MyClass:
    def __getitem__(self, key):
        return some_value_related_to_key

    def __setitem__(self, key, value):
        # set value (if needed)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM