“id”在Python中是一个错误的变量名

2024-04-25 07:38:46 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么在Python中命名变量id是不好的?


Tags: id命名
3条回答

id()是一个基本的内置:

Help on built-in function id in module __builtin__:

id(...)

    id(object) -> integer

    Return the identity of an object.  This is guaranteed to be unique among
    simultaneously existing objects.  (Hint: it's the object's memory
    address.)

一般来说,在任何语言中使用使关键字或内置函数黯然失色的变量名都是一个坏主意,即使这是允许的。

id是一个内置函数,它提供对象的内存地址。如果您命名一个函数id,则必须说__builtins__.id才能获得原始函数。全局重命名id除了小脚本之外,其他任何操作都会让人感到困惑。

但是,只要使用的是本地的,将内置名称作为变量重用并没有那么糟糕。Python有很多内置函数,这些函数(1)有共同的名称,(2)无论如何都不会使用太多。将它们用作局部变量或对象的成员是可以的,因为从上下文中可以明显看出您在做什么:

示例:

def numbered(filename):
  file = open(filename)
  for i,input in enumerate(file):
    print "%s:\t%s" % (i,input)
  file.close()

一些内置的诱人名字:

  • id
  • file
  • list
  • map
  • allany
  • complex
  • dir
  • input
  • slice
  • buffer

PEP 8-Style Guide for Python代码中,以下指导出现在Descriptive: Naming Styles 部分:

  • single_trailing_underscore_ : used by convention to avoid conflicts with Python keyword, e.g.

    Tkinter.Toplevel(master, class_='ClassName')

因此,要回答这个问题,应用本指南的一个例子是:

id_ = 42

在变量名中包含尾随下划线可以清楚地表明意图(对于熟悉PEP8中的指导的人)。

相关问题 更多 >