python常量
文章目录
前言
在其他语言中,我们可以定义一些常量,这些常量值在整个程序生命周期中不会改变。例如C/C++中有const关键字来声明常量,然后python却没有真正意义上的常量,python中该如何使用常量呢?
1. 通过命名风格
我们常以字母全大写,字母与字母之间用下划线连接来约定这个变量是常量,例如WINDOW_WIDTH, STUDENT_NAME。但是缺点就是这种只是约定,程序运行期间仍然可以更改该变量所属值
2. 使用自定义类
新建文件名const.py,内容如下
from typing import Any
class 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] = value
import sys
sys.modules[__name__] = Const() # Const单例作为const模块测试文件test_const.py
import const # 同级目录下
# const.name = "hello" # const.constCaseError
const.NAME = "hello"
print(const.NAME)
const.NAME = "world" # const.constError
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论