0

If I had the code:

names = ["Dave", "John", "Bob"]

and I wanted to get Dave from names I would do:

names[0]

If I now had the code

class Friends:
    def __init__(self, *people):
        self.names = []
        for v in people:
            self.names.append(v)

names = Friends("Dave", "John", "Bob")

to get Dave now I would have to do:

names.names[0]

Is there a magic method or something like that so that I can do:

names[0]

again and get Dave?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

5

Yes, it's called __getitem__ as in:

class MyClass:
    def __init__(self):
        self.names = ["john", "arthur"]

    def __getitem__(self, i):
        return self.names[i]

print(MyClass()[0])
# john
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
qmeeus
  • 2,341
  • 2
  • 12
  • 21