Python定义常量

时间:2023-02-15 20:14:56

用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()