2011-06-14 65 views
29

我的編輯器(TextMate)以其他顏色(當用作變量名稱)顯示id,然後顯示我通常的變量名稱。它是一個關鍵字嗎?我不想遮陽任何關鍵字...在idthon中`id`是關鍵字嗎?

回答

47

id不是一個Python 關鍵字,但它是一個built-in function的名稱。

關鍵字are

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 
+1

感謝您的快速回復。我假設在'class'中使用'id'作爲屬性是一樣的嗎? 'myobject = myclass(); myobject.id = 123;'這是否會影響內置功能? – Aufwind 2011-06-14 22:27:27

+7

@Aufwind:使用'id'作爲類屬性並不是很糟糕,因爲在Python中你總是要用某些東西('this.id'或'foo.id')來限定它,所以它總是遵循'.' 。你的編輯可能不理解這個區別。 – 2011-06-14 22:30:55

+1

隨意編輯和添加關鍵字。 – Trufa 2011-06-14 22:31:39

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.) 
13

您還可以從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.) 
+0

謝謝,我只是在python中忘記了(強大的)文檔。 :-) – Aufwind 2011-06-14 22:36:05

+0

如果'somecommand'可能是一個關鍵字或python內置函數可以肯定,我可以每次使用'help(somecommand)'嗎? – Aufwind 2011-06-16 18:01:24

+4

@Aufwind是的,你可以。但是,對於關鍵字,你必須使用一個字符串作爲'if'語句,你必須'help'('if')'。 – joaquin 2011-06-16 22:31:00

6

只爲reference purposes

檢查,如果事情是一個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'] 
相關問題