在Python中实现类似列表的索引访问 [英] Implement list-like index access in 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?
推荐答案
您需要编写或覆盖<一个href=\"http://docs.python.org/reference/datamodel.html#object.__getitem__\"><$c$c>__getitem__$c$c>, <一href=\"http://docs.python.org/reference/datamodel.html#object.__setitem__\"><$c$c>__setitem__$c$c>,和<一个href=\"http://docs.python.org/reference/datamodel.html#object.__delitem__\"><$c$c>__delitem__$c$c>.
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屋!