【问题标题】:What are built-in identifiers in Python?Python 中的内置标识符是什么?
【发布时间】:2016-11-16 19:40:35
【问题描述】:

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

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

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

【问题讨论】:

  • 标准例外是builtin 的一部分,它们的名称只是标识符,而不是关键字。试试import builtins; for identifier in dir(builtins): print(identifier)。它应该打印每个内置异常以及其他内置的名称/标识符。
  • @wwii 这些并不是python知道的所有标识符,例如cls缺失,__new____init__
  • @defoe 是 cls 内置标识符还是用作类对象名称的约定?如果您将字符串分配给名称 cls,您是否会隐藏 Python 本身使用的标识符? ...What is the 'cls' variable used for in Python classes?
  • 是的,cls 似乎不是内置标识符,但 __init____new__ 应该是。
  • 我刚刚评论了here 想知道特殊的方法名称。

标签: python python-2.7


【解决方案1】:

您可以使用以下命令获取所有内置函数...

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.

【讨论】:

    【解决方案2】:

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

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

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

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

    【讨论】:

      【解决方案3】:

      这正是你想的那样,一个不是函数的东西的名称,也不是像“while”这样的命令,是 Python 内置的。例如

      函数类似于open(),关键字类似于while,标识符类似于True,或IOError

      更多:

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

      标识符(也称为名称)

      【讨论】:

        【解决方案4】:

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

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

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

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2014-09-17
          • 2018-09-22
          • 1970-01-01
          • 2010-12-26
          • 1970-01-01
          • 2017-05-13
          • 2011-04-20
          相关资源
          最近更新 更多