python with语句中的变量有作用域吗?

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

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

举例:

# test.py

with 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

猜你喜欢

转载自www.cnblogs.com/zjutzz/p/9314255.html