Home > OS >  Python - Access a list from a class using instance[]
Python - Access a list from a class using instance[]

Time:03-05

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 !

CodePudding user response:

Define the __getitem__ function to allow for custom indexing:

def __getitem__(self, index):
    return self.matrice.__getitem__(index)
  • Related