Python中的内置标识符是什么?

时间:2016-07-14 03:10:31

标签: python python-2.7

我正在阅读Python tutorial并遇到了我无法理解的这一行:

  

标准异常名称是内置标识符(不保留   关键字)。

built-in identifiers是什么意思?我知道有一些内置函数,如open(),即我们不需要导入的函数。

4 个答案:

答案 0 :(得分:3)

这正是你的想法,一个不是函数的东西的名字,并不是像“while”那样的命令,并且内置于Python。 e.g。

功能类似open(),关键字类似while,标识符类似TrueIOError

更多人:

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 
'BufferError', 'BytesWarning', 'DeprecationWarning', 'EOFError', 'Ellipsis',
 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 
'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 
'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 
'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 
'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 
'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 
'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 
'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 
'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 
'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', 
'_', '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs', 
'all', 'any', 'apply', 'basestring', 'bin', 'bool', 'buffer', 'bytearray', 
'bytes', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 
'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 
'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 
'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 
'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 
'list', 'locals', 'long', 'map', 'max', 'memoryview', 'min', 'next', 'object', 
'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'raw_input', 
'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 
'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 
'unicode', 'vars', 'xrange', 'zip']

文档备份:

https://docs.python.org/2/reference/expressions.html

  

5.2。原子   原子是表达式中最基本的元素。最简单的原子是标识符或文字

     

作为原子出现的标识符是名称

https://docs.python.org/2/reference/lexical_analysis.html#identifiers

  

标识符(也称为名称)

答案 1 :(得分:1)

在Python中,标识符是给予特定实体的名称,无论是类,变量,函数等。例如,当我写:

some_variable = 2
try:
    x = 6 / (some_variable - 2)
except ZeroDivisionError:
    x = None

some_variablex都是我定义的标识符。这里的第三个标识符是ZeroDivisionError例外,它是一个内置标识符(也就是说,您无需导入或定义它,然后才能使用它)

这与保留关键字形成对比,后者无法识别对象,而是帮助定义Python语言本身。其中包括importforwhiletryexceptifelse等等。

答案 2 :(得分:1)

标识符是'变量名'。内置函数是Python附带的内置对象,不需要导入。它们与标识符相关联的方式与我们将foofoo = 5关联起来的方式相同。

关键字是def等特殊令牌。标识符不能是关键字;关键字是“保留”。

对于内置关键字,例如open,您可以使用具有相同拼写的标识符。因此,您可以说open = lambda: None,并且您已覆盖或“遮蔽”之前与名称open相关联的内置内容。影响内置插件通常不是一个好主意,因为它会增强可读性。

答案 3 :(得分:0)

您可以使用以下命令获取所有内置文件...

dir(__builtins__)

它将提供以下输出

>>> dir(__builtins__)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']

然后,如果您想检查我们可以对这些内置函数做什么,下面将给出定义help("<name_of_the_builin_function>")

>>> help("zip")
Help on class zip in module builtins:

class zip(object)
 |  zip(iter1 [,iter2 [...]]) --> zip object
 |  
 |  Return a zip object whose .__next__() method returns a tuple where
 |  the i-th element comes from the i-th iterable argument.  The .__next__()
 |  method continues until the shortest iterable in the argument sequence
 |  is exhausted and then it raises StopIteration.
 |  
 |  Methods defined here:
 |  
 |  __getattribute__(self, name, /)
 |      Return getattr(self, name).
 |  
 |  __iter__(self, /)
 |      Implement iter(self).
 |  
 |  __new__(*args, **kwargs) from builtins.type
 |      Create and return a new object.  See help(type) for accurate signature.
 |  
 |  __next__(self, /)
 |      Implement next(self).
 |  
 |  __reduce__(...)
 |      Return state information for pickling.
相关问题