听说你会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作为了函数的参数,从而得到定义
'''

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值