‘id’ 是 Python 中的一个错误变量名[重复]
- 2025-02-10 08:57:00
- admin 原创
- 51
问题描述:
为什么在 Python 中命名变量是不好的id
?
解决方案 1:
id()
是一个基本的内置功能:
id
模块
内置函数的帮助__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.)
一般来说,在任何语言中使用掩盖关键字或内置函数的变量名都是一个坏主意,即使这是允许的。
解决方案 2:
在PEP 8 - Python 代码样式指南中,描述性:命名样式部分中出现了以下指导:
single_trailing_underscore_
:按照惯例使用,以避免与 Python 关键字冲突,例如
Tkinter.Toplevel(master, class_='ClassName')
因此,为了回答这个问题,应用该指南的一个例子是:
id_ = 42
在变量名中包含尾随下划线可以使意图更清晰(对于熟悉 PEP 8 中的指导的人来说)。
解决方案 3:
我可能会在这里说一些不受欢迎的话:id()
是一个相当专业的内置函数,在业务逻辑中很少使用。因此,我认为在紧凑且编写良好的函数中将其用作变量名没有问题,因为很明显 id 并不意味着内置函数。
解决方案 4:
id
是一个内置函数,它给出对象的身份(在 CPython 中也是它的内存地址)。如果你将某个函数命名为id
,则必须说builtins.id
获取原始函数(或__builtins__.id
在 CPython 中)。id
全局重命名在除小脚本之外的任何脚本中都令人困惑。
但是,只要是在本地使用,将内置名称重用为变量也并不是一件坏事。Python 有很多内置函数,它们 (1) 具有通用名称,并且 (2) 无论如何您都不会经常使用。将它们用作局部变量或对象的成员是可以的,因为从上下文中可以明显看出您在做什么:
例子:
def numbered(filename):
with open(filename) as file:
for i, input in enumerate(file):
print("%s: %s" % (i, input), end='')
一些名字很诱人的内置函数:
id
list
,dict
map
all
,any
complex
,int
dir
input
slice
sum
min
,max
object
file
(在 Python 3.0 中删除)buffer
(在 Python 3.0 中删除)
解决方案 5:
其他人提到这很令人困惑,但我想详细说明一下原因。这是一个基于真实故事的例子。基本上,我编写了一个接受id
参数的类,但后来尝试使用内置函数id
。
class Employee:
def __init__(self, name, id):
"""Create employee, with their name and badge id."""
self.name = name
self.id = id
# ... lots more code, making you forget about the parameter names
print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))
tay = Employee('Taylor Swift', 1985)
预期输出:
Created Employee 'Taylor Swift' at 0x7efde30ae910
实际产量:
Traceback (most recent call last):
File "company.py", line 9, in <module>
tay = Employee('Taylor Swift', 1985)
File "company.py", line 7, in __init__
print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))
TypeError: 'int' object is not callable
嗯?我在哪里尝试调用 int?这些都是内置函数……
如果我将其命名badge_id
或id_
,我就不会遇到这个问题。
更新:幸运的是,这部分错误在 Python 3.11+ 中更加清晰:
print('Created', type(self).__name__, repr(name), 'at', hex(id(self)))
^^^^^^^^
解决方案 6:
用内置函数命名变量是不好的。原因之一是,这可能会让不知道名称被覆盖的读者感到困惑。
解决方案 7:
id
是 Python 中的内置函数。为 赋值id
将覆盖该函数。最好添加前缀(如 )some_id
或使用不同的大写形式(如 )ID
。
内置函数接受一个参数并返回您传递的对象的内存地址的整数(在 CPython 中)。
>>> id(1)
9787760
>>> x = 1
>>> id(x)
9787760
解决方案 8:
因为它是一个内置函数的名称。
解决方案 9:
因为 Python 是一种动态语言,所以给变量和函数赋予相同的名称通常不是一个好主意。id() 是 Python 中的一个函数,因此建议不要使用名为 id 的变量。请记住,这适用于您可能使用的所有函数……变量不应与函数同名。