在 Python 中实现类似列表的索引访问 [英] Implement list-like index access in Python
本文介绍了在 Python 中实现类似列表的索引访问的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我希望能够使用类似数组的语法访问 python 对象的某些值,即:
I'd like to be able to access some values of a python object using array-like syntax, ie:
obj = MyClass()
zeroth = obj[0]
first = obj[1]
这可能吗?如果是这样,你如何在有问题的 python 类中实现它?
Is this possible? If so, how do you implement this in the python class in question?
推荐答案
您需要编写或覆盖 __getitem__
, __setitem__
和 __delitem__
.
You need to write or override __getitem__
, __setitem__
, and __delitem__
.
例如:
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.
这篇关于在 Python 中实现类似列表的索引访问的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文