前言

在其余语言中,咱们能够定义一些常量,这些常量值在整个程序生命周期中不会扭转。例如C/C++中有const关键字来申明常量,而后python却没有真正意义上的常量,python中该如何应用常量呢?

1. 通过命名格调

咱们常以字母全大写,字母与字母之间用下划线连贯来约定这个变量是常量,例如WINDOW_WIDTH, STUDENT_NAME。然而毛病就是这种只是约定,程序运行期间依然能够更改该变量所属值

2. 应用自定义类

新建文件名const.py,内容如下

from typing import Anyclass Const:    class ConstCaseError(SyntaxError):        pass    class ConstError(SyntaxError):        pass    def __setattr__(self, name: str, value: Any) -> None:        if self.__dict__.get(name):            raise self.ConstError("Can't chang const.{name}".format(name=name))        if not name.isupper():            raise self.ConstCaseError("const name {name} is not uppercase".format(name=name))        self.__dict__[name] = valueimport syssys.modules[__name__] = Const()  # Const单例作为const模块

测试文件test_const.py

import const  # 同级目录下# const.name = "hello"  # const.constCaseErrorconst.NAME = "hello"print(const.NAME)const.NAME = "world"  # const.constError