Equivalent __index__ method in Micropython
Posted: Tue Apr 28, 2020 11:38 am
In CPython, there is a class 'magic' method '__index__()' which allows the object to be used in slice notation:
I tried to replicate this in Micropython but it seems it does not use the same method for slicing or indexing. I could add an method to my class, and then call but that is just as messy as
Can someone explain what methods are called when an object is used as an index? Or is it simply that it type-checks the object to make sure its an integer and then just gets the value?
Code: Select all
class Screen_Object(object):
def __init__(x_pos, y_pos, index)
self.x = x_pos
self.y = y_pos
self.screen_list_index = index
def draw_object(self):
#draw instructions
def __index__(self):
return self.screen_list_index
title = Screen_Object(200,200, 1)
all_screen_objects = ['background', 'title', 'text', 'icon']
>>> all_screen_objects[title]
'title'
Code: Select all
'__int__()'
Code: Select all
all_screen_objects[int(title)]
Code: Select all
all_screen_objects[title.screen_list_index]