如何在Python中覆盖[]运算符? [英] How to override the [] operator in Python?
本文介绍了如何在Python中覆盖[]运算符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
为Python中的类覆盖[]
运算符(下标表示法)的方法的名称是什么?
What is the name of the method to override the []
operator (subscript notation) for a class in Python?
推荐答案
You need to use the __getitem__
method.
class MyClass:
def __getitem__(self, key):
return key * 2
myobj = MyClass()
myobj[3] #Output: 6
如果要设置值,则需要实现 __setitem__
方法,否则会发生这种情况:
And if you're going to be setting values you'll need to implement the __setitem__
method too, otherwise this will happen:
>>> myobj[5] = 1
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
这篇关于如何在Python中覆盖[]运算符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文