python实现常量const

新建const.py:

#-*-coding:UTF-8-*-

#Filename: const.py

# 定义一个常量类实现常量的功能

# # 该类定义了一个方法__setattr()__,和一个异常ConstError, ConstError类继承

# 自类TypeError. 通过调用类自带的字典__dict__, 判断定义的常量是否包含在字典

# 如果字典中包含此变量,将抛出异常,否则,给新创建的常量赋值。

# 最后两行代码的作用是把const类注册到sys.modules这个全局字典中。

class _const:

    class ConstError(TypeError):pass

    def __setattr__(self, name, value):

        if self.__dict__.has_key(name):

            raise self.ConstError, "Can't rebind const (%s)" %name

        self.__dict__[name]=value

import sys

sys.modules[__name__] = _const()

 新建test.py:

#-*-coding:UTF-8-*-

import const

const.magic = 23

print const.magic

const.magic = 33

 

结果:

 

posted @ 2018-10-02 14:50  夏晓旭  阅读(9173)  评论(0编辑  收藏  举报