python - 覆盖Python中的内置函数

标签 python keyword

如果我无意中覆盖/屏蔽 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/

相关文章:

python - 从内核推断特定值的概率

python - Django-CKEditor 图片上传

php - 是否有可能 "escape"PHP 中的方法名称,以便能够拥有与保留关键字冲突的方法名称?

c# - 在枚举中使用静态

c - C 中 __IO 和 static 关键字的用途是什么?

python - 按顺序执行函数

python - Django 从 linkedin 导入用户配置文件

typescript - 为什么 Typescript 需要 infer 关键字?

python - Django 枪兽 : Error when calling the metaclass bases

Mysql查找文本中的关键字