如何使用__getitem__
执行此类操作?
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')
答案 0 :(得分:3)
是的,你可以。在这两种情况下,都会使用一个对象调用__getitem__
方法。在第一种情况下,传递一个字符串对象,在第二种情况下,传递一个包含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'