Can generators be used to create Objects? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Can generators be used to create Objects?

class MyClass: def __init__(self, data): self.Data = data def generate(list): for x in list: yeid myclass(list[x].data) is this valid? how do i access the generated data? listOfMyClass = list(generate(input))????

11th Oct 2016, 4:33 PM
David Queen
1 Answer
0
I'm notgood with classes and I cannot understand what you are trying to do wit the class in here. However in generator you cannot really access data as in a list. You can only go throu each element once, like so: print next (dataFromGenerator) there is no moving back with this. I just saw an excellent youtube video on generators by Corey Shafer, very useful. If you have more questions after watching it (and maybe modifying the code), type as well some example code you want to run after those definitions and what output you expect, like x = [1,2,3] generate(x) ## I expect [1,4,9], but I get a ValueError in line 6 Note on a side - remember that Python is case sensitive, so 6th line should generate an error (on both myclass and data). Also list[x] is not how you do in for loop. use x by it self instead. "for x in list:" breaks for you list into pieces and takes only one piece each time, and calls it "x" for this particular iteration. In other words for the first iteration x = list[0], for the second one x = list[1] and so on.
7th Nov 2016, 3:13 PM
Chris
Chris - avatar