python常量

Posted chenliang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

以上是关于python常量的主要内容,如果未能解决你的问题,请参考以下文章

python 有用的Python代码片段

Python 向 Postman 请求代码片段

python [代码片段]一些有趣的代码#sort

使用 Python 代码片段编写 LaTeX 文档

Python 3学习笔记

python 机器学习有用的代码片段