`id` 是 Python 中的关键字吗?

80 投票
4 回答
35497 浏览
提问于 2025-04-16 19:34

我的编辑器(TextMate)把 id 这个词显示成了不同的颜色(当它作为变量名使用时),和我平常用的变量名颜色不一样。这是个关键字吗?我不想把任何关键字弄成阴影...

4 个回答

15

仅供参考

检查某个东西是否是Python中的关键字:

>>> import keyword  
>>> keyword.iskeyword('id')
False

查看Python中的所有关键字:

>>> keyword.kwlist
['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif',
 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import',
 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try',
 'while', 'with', 'yield']
23

你也可以向Python寻求帮助:

>>> help(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.)

或者你可以问问IPython。

IPython 0.10.2   [on Py 2.6.6]
[C:/]|1> id??
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in function id>
Namespace:      Python builtin
Docstring [source file open failed]:
    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.)
104

id 不是 Python 中的一个 关键字,而是一个 内置函数 的名字。

Python 的关键字 包括

and       del       from      not       while
as        elif      global    or        with
assert    else      if        pass      yield
break     except    import    print
class     exec      in        raise
continue  finally   is        return
def       for       lambda    try

关键字不能用作变量名。如果你尝试这样做,就会出现语法错误:

if = 1

另一方面,像 idtypestr 这样的内置函数是可以被覆盖的:

str = "hello"    # don't do this

撰写回答