我对“Learning Python”一书中的代码有点困惑,p。539.
据我所知,函数内的分配仅在此本地范围内。所以如果我想改变一个全局的,我首先必须声明它global
。但是为什么下面的代码一旦调用builtin.open()
就完全改变了?custom
import builtins
def makeopen(id):
original = builtins.open
def custom(*pargs, **kargs):
print('Custom open call %r: ' % id, pargs, kargs)
return original(*pargs, **kargs)
builtins.open = custom
如果我打电话makeopen('spam')
,F = open('text.txt')
然后我custom
接到电话。所以.builtin.open()
之后整个脚本中的makeopen('spam')
. 为什么?如果我再做一些,makeopen('xx')
就会为每个 createdbuiltin.open('text.txt')
打印调用。为什么?custom
makeopen
将此代码与
x = 99
def changing():
x = 88
changing()
print(x)
甚至不帮助我。不是一样,而是用一个x
代替builtin.open()
吗?