繁体   English   中英

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

[英]What are built-in identifiers in Python?

我正在阅读Python教程 ,碰到了我不明白的这一行:

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

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

正是您所想的那样,它不是函数,也不是“ while”之类的命令的名称,它是Python内置的。 例如

函数类似于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

标识符(也称为名称)

在Python中,标识符是赋予特定实体的名称,可以是类,变量,函数等。例如,当我编写时:

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

some_variablex都是我定义的标识符。 这里的第三个标识符是ZeroDivisionError异常,它是一个内置标识符(也就是说,在使用它之前,您不必导入或定义它)。

这与保留关键字形成对比, 保留关键字不标识对象,而是帮助定义Python语言本身。 这些包括importforwhiletryexceptifelse等。

标识符是“变量名”。 好的,内置对象是Python附带的内置对象,不需要导入。 它们与标识符关联的方式与我们通过说foo = 5可以将5与foo关联的方式相同。

关键字是特殊标记,例如def 标识符不能是关键字; 关键字为“保留”。

不过,对于像open这样的内置关键字,您可以使用具有相同拼写的标识符。 因此,您可以说open = lambda: None并且您已覆盖或“隐藏”了以前与名称open相关联的内置open = lambda: None 阴影内置组件通常不是一个好主意,因为它会增加可读性。

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

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.

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM