您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

如何在Python中覆盖[]运算符?

如何在Python中覆盖[]运算符?

您需要使用__getitem__方法

class MyClass:
    def __getitem__(self, key):
        return key * 2

myobj = MyClass()
myobj[3] #Output: 6

如果要设置值,则也需要实现该__setitem__方法,否则会发生这种情况:

>>> myobj[5] = 1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: MyClass instance has no attribute '__setitem__'
python 2022/1/1 18:41:04 有261人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶