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()
原文地址:https://www.cnblogs.com/MrWho/p/python-const.html