在python运算符重载中使用_ugetItem

在python运算符重载中使用_ugetItem,python,python-3.x,Python,Python 3.x,如何使用\uu getitem\uu执行类似操作 class Computers: def __init__(self, processor, ram, hard_drive): self.processor = processor self.ram = ram self.hard_drive = hard_drive 我想做的是 C = Computers('2.4 Ghz','4 gb', '500gb') C['h']返回50

如何使用
\uu getitem\uu
执行类似操作

class Computers:

    def __init__(self, processor, ram, hard_drive):
        self.processor = processor 
        self.ram = ram
        self.hard_drive = hard_drive
我想做的是

C = Computers('2.4 Ghz','4 gb', '500gb')
C['h']
返回500gb


C['p','r','h']
返回('2.4 Ghz','4 gb','500gb')

是的,您可以。在这两种情况下,您的
\uuu getitem\uu
方法都将使用一个对象调用。在第一种情况下,传递一个字符串对象,在第二种情况下,传递一个包含3个字符串的元组

处理两种情况:

def __getitem__(self, item):
    attrmap = {'p': 'processor', 'r': 'ram', 'h': 'hard_drive'}
    if isinstance(item, str):
        return getattr(self, attrmap[item])
    # assume a sequence
    return tuple(getattr(self, attrmap[i]) for i in item)
演示,包括错误处理:

>>> C = Computers('2.4 Ghz','4 gb', '500gb')
>>> C['h']
'500gb'
>>> C['p', 'r', 'h']
('2.4 Ghz', '4 gb', '500gb')
>>> C['f']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 9, in __getitem__
KeyError: 'f'
>>> C['p', 'r', 'f']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 11, in __getitem__
  File "<stdin>", line 11, in <genexpr>
KeyError: 'f'
C=计算机('2.4 Ghz'、'4 gb'、'500gb') >>>C['h'] “500gb” >>>C['p','r','h'] (‘2.4 Ghz’、‘4 gb’、‘500gb’) >>>C['f'] 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“”,第9行,在\uu getitem中__ 键错误:“f” >>>C['p','r','f'] 回溯(最近一次呼叫最后一次): 文件“”,第1行,在 文件“”,第11行,在\uu getitem中__ 文件“”,第11行,在 键错误:“f”