[英]How to override the [] operator in Python?
在 Python 中为类覆盖[]
运算符(下标符号)的方法的名称是什么?
You need to use the __getitem__
method .您需要使用
__getitem__
方法。
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
And if you're going to be setting values you'll need to implement the __setitem__
method too, otherwise this will happen:如果你要设置值,你也需要实现
__setitem__
方法,否则会发生这种情况:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
To fully overload it you also need to implement the __setitem__
and __delitem__
methods.要完全重载它,您还需要实现
__setitem__
和__delitem__
方法。
edit编辑
I almost forgot... if you want to completely emulate a list, you also need __getslice__, __setslice__ and __delslice__
.我差点忘了……如果你想完全模拟一个列表,你还需要
__getslice__, __setslice__ and __delslice__
。
There are all documented in http://docs.python.org/reference/datamodel.html在http://docs.python.org/reference/datamodel.html中都有记录
You are looking for the __getitem__
method.您正在寻找
__getitem__
方法。 See http://docs.python.org/reference/datamodel.html , section 3.4.6请参阅http://docs.python.org/reference/datamodel.html ,第 3.4.6 节
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.