Python关键字

2023-09-17 22:14:07

就像自然语言一样,计算机编程语言由一组预定义的单词组成,这些单词称为关键字。每个关键字的规定使用规则称为语法。

Python 3.x 有 33 个关键字。由于它们附加了预定义的含义,因此不能用于任何其他目的。Python 关键字列表可以使用 Python shell 中的以下帮助命令获取。

>>>help("keywords")

下表列出了 Python 中的所有关键字。

Falsedefifraise
Nonedelimportreturn
Trueelifintry
andelseiswhile
asexceptlambdawith
assertfinallynonlocalyield
breakfornot
classfromor
continueglobalpass

除了前三个关键字(False、None 和 True)之外,其他关键字完全为小写。

使用help()命令了解有关每个关键字的更多信息。以下内容将显示有关global关键字的信息。

>>>help("global")

保留标识符(Reserved Identifiers)

Python 内置类包含一些具有特殊含义的标识符。 这些特殊标识符由前导和尾随下划线字符的模式识别:

PatternDescriptionExamples
_*_ stores the result of the last evaluation.
>>> 5 * 5 
 25
 >>> _
 25
__*__It represents system-defined identifiers that matches __*__ pattern, also known as dunder names. These can be functions or properties such as __new__(), __init__(), __name__, __main__, etc.
 >>> __name__
 '__main__'
__*It represents class's private name pattern. These names are to be used with private member names of the class to avoid name clashes between private attributes of base and derived classes.

本文内容总结: