def firstn(n): num = 0 while num<n : yield num num += 1 class FirstN(object): class Iterator(object) : def __init__ (self,start,n) : self.max = n self.start = start def next(self) : if self.start >= self.max: raise StopIteration current = self.start self.start += 1 return current def __init__ (self,start,n) : self.min = start self.max = n+start def __str__(self): return "Numbers from "+str(self.min)+ " to " + str(self.max-1) def __iter__(self) : return self.Iterator(self.min,self.max) def __getitem__(self,idx):return str(self.min+idx) @property def ffrom(self): return self.min @ffrom.setter def ffrom(self,value): self.min=value def get_tto(self): return self.max def set_tto(self,value): self.max=value def sum2(i): it = i.__iter__() sv = 0 try: while True: val = it.next() sv += val except StopIteration: print("Iteration done.") return sv fn = FirstN(30,100) fn.ffrom = 50 fn.fto = 150 print(fn.ffrom) print(fn.fto) print(fn[30]) #print(FirstN(100)) print(sum2(fn))
Run
Reset
Share
Import
Link
Embed
Language▼
English
中文
Python Fiddle
Python Cloud IDE
Follow @python_fiddle
Browser Version Not Supported
Due to Python Fiddle's reliance on advanced JavaScript techniques, older browsers might have problems running it correctly. Please download the latest version of your favourite browser.
Chrome 10+
Firefox 4+
Safari 5+
IE 10+
Let me try anyway!
url:
Go
Python Snippet
Stackoverflow Question