Python: How to assign function name dynamically in Class
<p>I have an question about how to assign function name dynamically in Class.</p>

<h2>For example:</h2>

<pre><code>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></pre>

<h2>Code:</h2>

<p>The sample is get fibonacci numbers within 10</p>

<pre><code>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 &gt; 10:
            raise StopIteration();
        return self.a
</code></pre>

<h2>Test:</h2>

<pre><code>for i in Fib():
    print(i)
</code></pre>

<h2>Expected Result should be:</h2>

<pre><code>('iter_n value is ', 'next')
1
1
2
3
5
8
</code></pre>

<h2>Actual Result:</h2>

<pre><code>('iter_n value is ', 'next')
Traceback (most recent call last):
......
TypeError: iter() returned non-iterator of type 'Fib'
</code></pre>

<p>Code will be able to get the right results</p>

<ul>
<li>for python 2, if I replace <code>def iter_n(self)</code> to <code>def next(self)</code></li>
<li>for python 3, if I replace <code>def iter_n(self)</code> to <code>def __next__(self)</code></li>
</ul>

<h2>Question:</h2>

<p>How should I put <code>next</code> or <code>__next__</code> to <code>iter_n</code> dynamically?</p>

<p>In python there is the way to call a function ,method ,get any element by using getattr(from,'name of attribute to call').</p>

<p>below is the sample example of this:</p>

<pre><code>class A():
    def s(self):
            print "s fun"
    def d(self):
            print "a fun"
    def run(self):
            print "in run"

def main():
    print "in main"
    classA = A()
    func_list = ['s','d','run']
    for i in func_list:
            func = getattr(classA,i)
            func()

main()
</code></pre>

<p>Try to use this to call function dynamically.</p>

python