Can anyone plzz explain me little bit about magic mathods..and operator overloading.. | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can anyone plzz explain me little bit about magic mathods..and operator overloading..

import random class VagueList: def __init__(self, cont): self.cont = cont def __getitem__(self, index): return self.cont[index + random.randint(-1, 1)] def __len__(self): return random.randint(0, len(self.cont)*2) vague_list = VagueList(["A", "B", "C", "D", "E"]) print(len(vague_list)) print(len(vague_list)) print(vague_list[2]) print(vague_list[2]) plz help me with this code..!!

23rd Sep 2020, 2:30 PM
Srishti
Srishti - avatar
4 Answers
+ 3
Operator overloading is basically YOU deciding what subtracting two things, finding the length of something, ect actually does. In your code, the vauge list has 1 attribute: self.cont. (it just looks like the CONTents of the list) With that in mind, now look at the def __len__ line. You can check the length of most data types, but its most usable in iterables (lists, tuples, blah). When you define any magic method, you are changing how the class handles those built in methods. So when you call len() on a vauge list class object, instead of returning the number of items in the iterable, it returns a number from 0 to (The actual length of the list) * 2
23rd Sep 2020, 3:16 PM
Slick
Slick - avatar
+ 2
Can you be more precise with the question? which part you need help with? you forgot to say that. Just an insight ... __getitem__ magic method is the one responsible for handling request to an element by a given index. __len__ magic method is the one responsible for counting the elements contained.
23rd Sep 2020, 3:12 PM
Ipang
+ 1
Right, read the last post over. Each value is just a random value. The first two are explained above and the last two are random choices from the list you fed to the vaguelist class.
24th Sep 2020, 2:18 PM
Slick
Slick - avatar
0
Actually i having a problem with the result of the code..! that is >>> 6 7 D C >>> can you plzz explain me the result..!
24th Sep 2020, 2:06 PM
Srishti
Srishti - avatar