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

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

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

Okay