ProgrammingHardIBM · Deloitte pattern

What is printed?

What is printed?
class D:
    def __getitem__(self, key):
        if isinstance(key, slice):
            return f"slice {key.start}:{key.stop}:{key.step}"
        return f"item {key}"
d = D()
print(d[3])
print(d[1:5:2])
  1. A. item 3 slice 1:5:2
  2. B. 3 1:5:2
  3. C. item 3 TypeError
  4. D. slice 3 slice 1:5:2

Correct answer: A. item 3 slice 1:5:2

d[3] passes the plain integer 3 as key. d[1:5:2] passes a slice object whose .start, .stop and .step attributes are 1, 5, 2, which __getitem__ detects with isinstance and formats accordingly.

More Python Programming questions

Exams that ask this topic