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

Auf*_*ind 46 python keyword

我的编辑器(TextMate)id用另一种颜色(当用作变量名)时显示我常用的变量名.它是关键字吗?我不想遮蔽任何关键字......

Gre*_*ill 60

id不是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
Run Code Online (Sandbox Code Playgroud)

关键字是无效的变量名称.以下是语法错误:

if = 1
Run Code Online (Sandbox Code Playgroud)

在另一方面,内置功能,如idtypestr可被阴影:

str = "hello"    # don't do this
Run Code Online (Sandbox Code Playgroud)

  • @Aufwind:使用`id`作为类属性并不是那么糟糕,因为在Python中你总是要用某些东西(`this.id`或`foo.id`)来限定它,所以它总是遵循`.`.你的编辑可能不理解这种区别. (9认同)
  • 我有时甚至将`id`用作局部变量而感到内疚.如果很少需要它就很容易不在乎...... (5认同)
  • 自由编辑和添加关键字。 (2认同)
  • 我无法想出一个与`id`一样短的同义词.很高兴听到,作为一种属性,它没有任何副作用.:-) (2认同)

joa*_*uin 17

你也可以从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.)
Run Code Online (Sandbox Code Playgroud)

或者你可以质疑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.)
Run Code Online (Sandbox Code Playgroud)

  • @Aufwind是的,你可以.但是,对于关键字,您必须使用字符串作为`if`语句,您必须执行`help('if')`. (5认同)

Ste*_*ker 8

仅供参考:

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

>>> import keyword  
>>> keyword.iskeyword('id')
False
Run Code Online (Sandbox Code Playgroud)

检查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']
Run Code Online (Sandbox Code Playgroud)


nak*_*tic 7

它是内置功能:

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.)
Run Code Online (Sandbox Code Playgroud)