Python定义常量

用Python实现常量

定义

# coding=utf-8
# const.py
class ConstAssignError(Exception): pass

class _const(object):
    def __setattr__(self, k, v):
        if k in self.__dict__:
            raise ConstAssignError, "Can't rebind const (%s)" % k
        else:
            self.__dict__[k] = v


def _test():
    const = _const()
    const.A = 1
    print const.A

    const.A = 1


if __name__ == '__main__':
    _test()
posted @ 2015-01-27 12:08  Mx.Hu  阅读(599)  评论(0编辑  收藏  举报