2

How can I do something like this using __getitem__?

class Computers:

    def __init__(self, processor, ram, hard_drive):
        self.processor = processor 
        self.ram = ram
        self.hard_drive = hard_drive

what I want to be able to do is

C = Computers('2.4 Ghz','4 gb', '500gb')

C['h'] to return 500gb

and C['p','r','h'] to return ('2.4 Ghz','4 gb', '500gb')

1 Answer 1

3

Yes, you can. In both cases, your __getitem__ method would be called with one object. In the first case, you are passed a single string object, in the second, you passed a 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 a sequence
    return tuple(getattr(self, attrmap[i]) for 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'
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.