I have an question about how to assign function name dynamically in Class.
For example:
If a class wants to be used for "for...in" loop, similar to a list
or a tuple, you must implement an __iter__ () method
python2.x will use __iter__() and next(),
python3.x need to use __iter__() and __next__()
Code:
The sample is get fibonacci numbers within 10
class Fib(object):
def __init__(self):
self.a, self.b = 0, 1
def __iter__(self):
return self
if sys.version_info[0] == 2:
iter_n = 'next' #if python version is 2.x
else:
iter_n = '__next__' #if python version is 3.x
print('iter_n value is ', iter_n)
#for py2 I want to replace "iter_n" to "next" dynamically
#for py3 I want to replace "iter_n" to "__next__" dynamically
def iter_n(self):
self.a, self.b = self.b, self.a + self.b
if self.a > 10:
raise StopIteration();
return self.a
Test:
for i in Fib():
print(i)
Expected Result should be:
('iter_n value is ', 'next')
1
1
2
3
5
8
Actual Result:
('iter_n value is ', 'next')
Traceback (most recent call last):
......
TypeError: iter() returned non-iterator of type 'Fib'
Code will be able to get the right results
- for python 2, if I replace
def iter_n(self)todef next(self) - for python 3, if I replace
def iter_n(self)todef __next__(self)
Question:
How should I put next or __next__ to iter_n dynamically?