Using __getitem__ in operator overloading with python -
how can using __getitem__
?
class computers: def __init__(self, processor, ram, hard_drive): self.processor = processor self.ram = ram self.hard_drive = hard_drive
what want able is
c = computers('2.4 ghz','4 gb', '500gb')
c['h']
return 500gb
and c['p','r','h']
return ('2.4 ghz','4 gb', '500gb')
yes, can. in both cases, __getitem__
method called 1 object. in first case, passed single string object, in second, passed tuple containing 3 strings.
handle both cases:
def __getitem__(self, item): attrmap = {'p': 'processor', 'r': 'ram', 'h': 'hard_drive'} if isinstance(item, str): return getattr(self, attrmap[item]) # assume sequence return tuple(getattr(self, attrmap[i]) in item)
demo, including error handling:
>>> 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'
Comments
Post a Comment