'Create new instance of a given object, using same arguments provided in __init__
Given any iterator, I want to be able to pass this iterator into my function, to return a new iter object that cycles through the given iter infinitely. E.G
class range:
def __init__(self, min, max, step):
self.min = min
self.max = max
self.step = counter
[...] other vars
def __next__(self):
if [.............]
You get the jist. I have a bunch of custom iterators like this, all created with diff args/params. I know I can use vars to get the variables... but how do you distinguish between vars passed into init to create this object, and others vars? Vars returnsmin/max/counter + all the other vars
I have a class like this:
class Cycle:
def __init__(self, iterable):
self.iterable = iterable
def __next__(self):
next_val = next(self.iterable, None)
if next_val is None:
#RESET iterable or create new instance of iterable with same _init_ args used to create it
next_val = next(self.iterable)
return next_val
Intended use:
r = range(0,4,2)
next(r) = 0
next(r) = 2
next(r) = 4
next(r) = stopiterationerror
c = Cycle(r)
next(c) = 0
next(c) = 2
next(c) = 4
next(c) = 0
next(c) = 2
next(c) = 4
....... I want to keep this cycle function clean and simple if I can. Ideally I would want to simply self.iterable.reset, but it seems like resetting an iterable is not possible in python and I need to create a brand new instance. I know I could pass in *args into cycle, but is it possible to avoid that?
edit currently working:
class Cycle:
def __init__(self, iterable):
self.iterable = iterable
self.copy = copy(iterable)
def __next__(self):
next_val = next(self.iterable, None)
if next_val is None:
self.iterable = self.copy
self.copy = copy(self.copy)
next_val = next(self.iterable, None)
return next_val
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
