0
class Foo:
    """
    class to represent 2D arrays
    """
    def __init__(self, lst: list[list]) -> None:
        self.lst = lst

a_list = [
    [1, 2, 3, 4],
    [5, 6, 7, 8],
    [9, 10, 100]
]

If I want to access 10 in my variable a_list. I type a_list[2][1]

What I am trying to do here is ...

I create an instance i.e Foo(a_list) and save it in a variable n. So, n = Foo(a_list) is what I type. Now, if I again want to access 10. I surely can access it by n.lst[2][1]

My question here, is there anyway I can do the same thing the following way: n[2][1] ?

1 Answer 1

1

This can be done using the __getitem__ method. Something like

class Foo:
    """
    class to represent 2D arrays
    """
    def __init__(self, lst: list[list]) -> None:
        self.lst = lst

    def __getitem__(self, idx):
        return self.lst[idx]

For your example, n[2] returns a list, so n[2][1] is indexing into a 'normal' python list.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.