+ 2

output of python programming

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]) output 6 7 D C >>> overriding of len()....?? indexing() use...??

7th Apr 2018, 5:34 PM
Smriti Rastogi
Smriti Rastogi - avatar
3 Antworten
+ 2
Nope! No overriding It's working according to your code: output of 6 and 7 are valid since your __len__ method returns a random value between 0 and 10 len(["A", "B", "C", "D", "E"]) * 2 == 5*2 == 10 So, you are actually doing a return of random.randint(0, 10). This will give different output for each call of ur len merhod. Same thing applies to outputs of vague_list[2]
8th Apr 2018, 8:40 AM
E_E Mopho
E_E Mopho - avatar
+ 2
Ok. When you created the object/instance vague_list, of class VagueList, u pass the list ["A","B","C","D","E"] to the argument cont. (the constructor handled this) the possible values of random.randint(-1, 1) are -1, 0, 1. vague_list[2] implies index = 2. Say random.randint(-1, 1) gives you 1; So return self.cont[index + random.randint(-1, 1)]==>return self.cont[2+1] ==>return ["A","B","C","D","E"][3] which gave the output D. If random.randint(-1, 1) gives you 0; it implies return self.cont[index + random.randint(-1, 1)] ==> return self.cont[2+0] ==> return ["A","B","C","D","E"][2] which gave output C. If random.randint(-1, 1) gave -1; U would get output B.
9th Apr 2018, 9:12 PM
E_E Mopho
E_E Mopho - avatar
0
how the functions are being called here....?? return self.cont[index + random.randint(-1, 1)] #WORKING OF THIS STATEMENT...?? Same thing applies to outputs of vague_list[2] #HOW...???
9th Apr 2018, 2:15 PM
Smriti Rastogi
Smriti Rastogi - avatar