博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
python with语句中的变量有作用域吗?
阅读量:4687 次
发布时间:2019-06-09

本文共 539 字,大约阅读时间需要 1 分钟。

一直以为python中的with语句中的变量,只在with语句块中起作用。不然为什么要缩进一个级别呢?

呵呵,然而并没有为with语句内的变量创建新的作用域。

举例:

# test.pywith open('test.txt', 'w') as fout:    a = 12    line = 'test line\n'    fout.write(line)print('a=', a)  #这里访问了a变量,会报错吗?并不会。

执行上述代码,发现最后一行的print语句并没有报错,因为with并没有为a新创建作用域。

类似的写法,出现在tensorflow eager入门教程的求导函数中:

def grad(model, inputs, targets):    with tf.GradientTape() as tape:        loss_value = loss(model, inputs, targets)    return tape.gradient(loss_value, model.variables)       #这里使用到了tape

转载于:https://www.cnblogs.com/zjutzz/p/9314255.html

你可能感兴趣的文章