听说你会python?第一题

#!/usr/bin/env python
#coding:utf8

def func2(x):
    """
    func2 is an easy way to understand func1, they are actually the same.
    You should understand what generator expression is, it looks like list comprehension.
    Refer to section 4.10 in python in a nutshell for list comprehension
    :param x:
    :return:
    """
    for _ in xrange(10):
        yield x

def func1(x):
    """
    func1 is another type of B.gen
    :param x:
    :return:
    """
    return (x for _ in xrange(10))

class C(object):
    x = 1
    gen=(lambda x:(x for _ in xrange(10)))(x)

class B(object):
    """
    gen is a lambda function object
    """
    x = 1
    gen=(lambda x:(x for _ in xrange(10)))

class A(object):
    """
    the problem is that variable inside a generator is excluded to the outside world,
    so the x in the generator is not defined
    """
    x = 1
    gen = (x for _ in xrange(10))

if __name__ == "__main__":
    #print(list(A.gen))
    f1 = func1(1)
    f2 = func2(2)
    print list(f1)
    print list(f2)
    print B.gen
    print list(C.gen)

'''
这个问题的根本原因是class A的gen是个generator,但是外面的x对这个generator是隔离的,所以它里面的x并未定义
于是报错global x is not defined
所以,要记住generator里面用到的所有变量都必须在内部定义,或者通过参数传递进来
其实class B和class C的解决办法就是使用lambda定义一个函数,使得generator的x作为了函数的参数,从而得到定义
'''

猜你喜欢

转载自blog.csdn.net/leonard_wang/article/details/58614253
今日推荐