Skip to content
Advertisement

Python – Access a list from a class using instance[]

So I have this code :

class matrix:
    def __init__(self, matriceOrigine: list) -> None:
        self.length = len(matriceOrigine)
        self.matrice = list(matriceOrigine)

    def transpose(self) -> list:
        pass

    def transition(self, lam: float) -> list:
        pass

And when I create an instance, like this :

foo = [[1,2,3],[4,5,6]]
foo2 = matrix(foo)

To access a value (like 3 for example), I know I should do

foo2.matrice[0][2]

and I would like to know how to access it using

foo2[0][2]

and still use

foo2.transpose()
foo2.length

Thanks in advance !

Advertisement

Answer

Define the __getitem__ function to allow for custom indexing:

def __getitem__(self, index):
    return self.matrice.__getitem__(index)
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement