Python中定义常量

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/cj675816156/article/details/79949856

Python中定义常量

const.py 中定义常量类,检查常量再次设置就抛出异常,常量不是大写字母就抛出异常

import sys


class _const:
    class ConstError(TypeError):
        pass

    class ConstCaseError(ConstError):
        pass

    def __setattr__(self, name, value):
        if name in self.__dict__:
            raise self.ConstError("Can't change const.%s" % name)

        if not name.isupper():
            raise self.ConstCaseError(
                "const name '%s' is not all uppercase" % name)
        self.__dict__[name] = value

    def __delattr__(self, name):
        if name in self.__dict__:
            raise self.ConstError("can't unbind const(%s)" % name)
        raise NameError(name)


sys.modules[__name__] = _const()

测试代码:test.py

import const


const.COMPANY = "CHINA"
const.NAME = 'chenjun'

print("company = {0}".format(const.COMPANY))
print("name = {0}".format(const.NAME))
阅读更多
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页