重新定义python内置函数 [英] Redefining python built-in function
问题描述
我正在编写一个 python 程序,作者编写了一个看起来像这样的函数
I'm working on a python program and the author has written a function that looks like this
def blah():
str = "asdf asdf asdf"
doStuff(str)
这似乎有效,尽管 str 是一个内置函数,不应用作变量.
This seems to work, even though str is a built in function and shouldn't be used as a variable.
这里究竟发生了什么?我的猜测是 str 将不再可用作函数,而只能在他编写的 blah() 函数的范围内使用.那是对的吗?这不会全局重新定义 str ,对吗?
What is actually happening here? My guess is str will no longer be usable as a function, but only in the scope of the blah() function he's written. Is that correct? This won't redefine str globally, right?
推荐答案
在内部,函数的局部变量表将包含 str
的条目,该条目将是该函数的局部变量.您仍然可以通过在 Py3 中执行 builtins.str
和在 Py2 中执行 __builtin__.str
来访问函数中的内置类.函数外的任何代码都看不到函数的任何局部变量,因此内置类可以安全地在其他地方使用.
Internally, the function's local variable table will contain an entry for str
, which will be local to that function. You can still access the builtin class within the function by doing builtins.str
in Py3 and __builtin__.str
in Py2. Any code outside the function will not see any of the function's local variables, so the builtin class will be safe to use elsewhere.
这里还有另一个警告/角落案例,在这个问题中进行了描述.本地表条目是在编译时创建的,而不是在运行时创建的,因此即使在分配 "asdf asdf asdf"
str 的全局定义> 给它:
There is another caveat/corner case here, which is described in this question. The local table entry is created at compile-time, not at runtime, so you could not use the global definition of str
in the function even before you assign "asdf asdf asdf"
to it:
def blah():
x = str(12)
str = "asdf asdf asdf"
doStuff(str)
将失败并返回 UnboundLocalError
.
这篇关于重新定义python内置函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!