0

how __iter__() works ?

I have tried to understand the magic method in python but I couldn't get through __iter__(). So help me if you know. I will post my code down here ############################################### # __len__ for len() checked # __getitem__ for indexing checked # __setitem__ for assigning to indexed values checked # __delitem__ for deleting indexed values checked # __iter__ for iteration over objects (e.g., in for loops) ?helpme if you know # __contains__ for in checked class VagueList: def __init__(self, cont): self.cont = cont def __getitem__(self, index): return self.cont[index] def __len__(self): return len(self.cont) def __setitem__(self,index,value): self.cont[index] = value def __delitem__(self,index): del self.cont[index] def __contains__(self,param1): return True if param1 in self.__dict__.keys() else False vague_list = VagueList(["A", "B", "C", "D", "E"]) print(len(vague_list)) vague_list[0]= "t" del vague_list[3] print(len(vague_list)) for i in range(len(vague_list)): print(vague_list[i]) print('cont' in vague_list) ######################################################

27th Jun 2021, 3:20 PM
Ibrahim Gidi
Ibrahim Gidi - avatar
3 Respuestas
+ 1
def __iter__(self): for i in range(self): yield self[i] # or even: def __iter__(self): for i in range(len(self.cont)): yield self.cont[i] # so you could do: for v in vague_list: print(v)
27th Jun 2021, 3:39 PM
visph
visph - avatar
0
__iter__ should be a generator function (ie using 'yield' keyword to return values wich should result from iterating the object)
27th Jun 2021, 3:27 PM
visph
visph - avatar
0
could u clarify that by coding, please?
27th Jun 2021, 3:35 PM
Ibrahim Gidi
Ibrahim Gidi - avatar