是True、False、None关键字或Python 3中的内置关键字



因此,在Python2。但在Python 3中,我有点困惑。

>>> import 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', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', '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']
>>> import keyword
>>> dir(keyword.kwlist)
['False', 'None', 'True', 'and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']

TrueFalseNone均存在于内置模块和keywords模式中。那我该怎么对待他们呢?作为内置类还是作为关键字?

它们是保留字内置值。来自Python 3的新功能:

TrueFalseNone是保留字。(2.6已经部分实施了对None的限制。)

这意味着您不能将它们用作名称,从而为它们指定不同的值。这可以防止意外屏蔽内置的singleton值:

>>> True = False
  File "<stdin>", line 1
SyntaxError: can't assign to keyword

另请参阅Guido van Rossum关于NoneTrueFalse的历史课:

我还是忘了回答None/True/False是文字还是关键字。我的答案是两者都是。它们是关键字,因为解析器就是这样识别它们的。它们是文字,因为这是它们在表达中的作用,因为它们代表恒定值。

TrueFalseNone分类为关键字后,Python编译器实际上可以优化它们的使用,因为您不能(直接)重新绑定这些名称。Python可以将它们作为常量而不是全局查找,这样会更快。

在Python3.4之前,编译器仍然会为这些对象发出全局查找,请参见问题16619。从Python 3.4开始,Python解析器被扩展为生成一个新的AST节点NameConstant,以确保它们在任何地方都被视为常量。

最新更新