如果我无意中覆盖/屏蔽 Python 中的内置函数,可能会出现什么问题?
我会遇到比访问本地函数而不是内置函数的明显陷阱更糟糕的事情吗?
例如:
def max(a, b):
pass
class MyCompileTool(object):
def __init__(self, id):
self.id = id
def compile(self):
min = "3.4.4"
...
甚至在一些官方模块中:argparse.add_argument(..., type, ...)
最佳答案
在这里,您不会覆盖内置 min
,您只需创建一个 min
本地变量,如果 compile
的后续代码将包含以下内容,则首选该变量调用 min
:
class MyCompileTool(object):
...
def compile(self):
min = "3.4.4"
x = min(1, 2)
# ^^^ "3.4.4".__call__(1, 2)
# This will throw exception because strings doesn't have __call__
x = min(3, 4)
# ^^^ __builtins__.min
要在整个模块中隐藏 min
,请在全局命名空间中执行此操作:
min = "3.4.4"
# Now all calls of min will go to that string
class MyCompileTool(object):
pass
有关 Python 中如何解析名称的更多信息,请查看文档:4.1. Naming and binding
关于python - 覆盖Python中的内置函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29798592/