Python:如何在Class中动态分配函数名称

bin*_*bjz 2 python

我有一个关于如何在Class中动态分配函数名称的问题.

例如:

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__()
Run Code Online (Sandbox Code Playgroud)

码:

样本的纤维蛋白数量在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
Run Code Online (Sandbox Code Playgroud)

测试:

for i in Fib():
    print(i)
Run Code Online (Sandbox Code Playgroud)

预期结果应为:

('iter_n value is ', 'next')
1
1
2
3
5
8
Run Code Online (Sandbox Code Playgroud)

实际结果:

('iter_n value is ', 'next')
Traceback (most recent call last):
......
TypeError: iter() returned non-iterator of type 'Fib'
Run Code Online (Sandbox Code Playgroud)

代码将能够获得正确的结果

  • 对于python 2,如果我替换def iter_n(self)def next(self)
  • 对于python 3,如果我替换def iter_n(self)def __next__(self)

题:

我应该怎么放next__next__iter_n动态?

小智 5

我认为不需要动态创建此方法.只需实施两者; 更清晰,更容易.并且您的代码将兼容Python 2/3,而无需if语句.

class Fib(object):
    def __init__(self):
        self.a, self.b = 0, 1

    def __iter__(self):
        return self

    def iter_n(self):
        self.a, self.b = self.b, self.a + self.b
        if self.a > 10:
            raise StopIteration();
        return self.a

    def next(self):
        return self.iter_n()

    def __next__(self):
        return self.iter_n()


if __name__ == '__main__':
    for i in Fib():
        print(i)
Run Code Online (Sandbox Code Playgroud)