zl程序教程

您现在的位置是:首页 >  后端

当前栏目

Python保留字(关键字)一览表

Python 关键字 一览表 保留字
2023-06-13 09:11:55 时间
与 C、C++、Java、C# 等语言不同,Python 没有定义常量的关键字,意即 Python 中没有常量的概念。为了实现与其他语言中功能相近的常量,可以使用 Python 面向对象的方法编写一个 常量 模块。

将以下代码保存为 test-const.py:


import sys

class _CONSTANT:

 class ConstantError(TypeError) : pass

 def __setattr__(self, key, value):

 if key in self.__dict__.keys():

 raise(self.ConstantError, 常量重新赋值错误! )

 self.__dict__[key] = value

sys.modules[__name__] = _CONSTANT()

#使用以下方式为 CONSTANT 这个 常量 赋值和调用:

CONSTANT =_CONSTANT()

CONSTANT.TEST = test 

print(CONSTANT.TEST)

#尝试使用以下方式为 CONSTANT 重新赋值:

CONSTANT.TEST = test111 

print(CONSTANT.TEST)

程序执行结果如下所示:

C:/Users/Administrator/.spyder-py3/Python test-const.py 
test
Traceback (most recent call last):
  File test-const.py , line 35, in module
  CONSTANT.TEST = test111
  File test-const.py , line 27, in __setattr__
  raise(self.ConstantError, 常量重新赋值错误! )
TypeError: exceptions must derive from BaseException

可以看到,第一次为 CONSTANT.TEST 赋值后能够成功执行,当尝试为 CONSTANT.TEST 重新赋值时将会出现错误提示,这相当于起到了常量的作用。

保留字即其他语言中的关键字,是指在语言本身的编译器中已经定义过的单词,具有特定含义和用途,用户不能再将这些单词作为变量名或函数名、类名使用。Python 3.7.2 中的保留字主要有 False、None 等 35 个。

温馨提示:Python 3.7.2 中的 35 个保留字
False、None、True、and、as、assert、async、await、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.

Python 2.X 中的 exec 和 print 等保留字在 3.X 中已经改为内置函数。 Python 3.7.2 中 35 个保留字的含义及作用如表 1 所示。


在 Python 环境下可以执行以下命令查看当前版本的保留字:

import keyword
keyword.kwlist

程序执行结果如下:

import keyword
keyword.kwlist
[ False , None , True , and , as , assert , async , await , 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 ]

若将保留字作为标识符并赋值将会得到语法错误,如下所示。

>  File stdin , line 1
  >  ^
SyntaxError: invalid syntax

21382.html

cjavapython