DEV Community

pacdev
pacdev

Posted on

1

Data Model (__getitem__())

Data Model

Quand dans un script Python on fait my_object[i] c'est que l'objet my_object est une instance d'une classe qui a une méthode spéciale __getitem__(self) . Un exemple ci dessous.

Sans la méthode spéciale

class Building:
    def __init__(self, n_flats):
        self.__flats = [i for i in range(n_flats)]

building = Building(10)

building[4]
Enter fullscreen mode Exit fullscreen mode
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Input In [1], in <module>
      3         self.__flats = [i for i in range(n_flats)]
      5 building = Building(10)
----> 7 building[4]
​
TypeError: 'Building' object is not subscriptable
Enter fullscreen mode Exit fullscreen mode

Avec

class Building:
    def __init__(self, n_flats):
        self.__flats = [i for i in range(n_flats)]

    def __getitem__(self, i):
        return f"You have selected the building #{self.__flats[i]}"

building = Building(10)

building[4]
Enter fullscreen mode Exit fullscreen mode
'You have selected the building #4'
Enter fullscreen mode Exit fullscreen mode

L'utilisation de '[i]' est un raccourcis de my_object.__getitem__(). Une liste par exemple est une instance de classe qui a cette méthode implémentée

Source

Fluent Python - Luciano Ramalho

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay