您的位置:首页 > 编程语言 > Python开发

Python Cookbook学习记录 ch6_2_2013/11/7

2013-11-07 22:06 495 查看
6.2 定义常量

常量是指一旦初始化后就不能修改的固定值。c++中使用const保留字指定常量,而python并没有定义常量的保留字。但是python是一门功能强大的语言,可以自己定义一个常量类来实现常量的功能。

# -*- 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()


这样就完成了一个常量类的定义,我们可以在const.py中调用const类。

>>> import const
>>> const.majic =23
>>> const.majic =88

Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
const.majic =88
File "const.py", line 5, in __setattr__
raise self.ConstError, "Can't rebind const(%s)" % name
ConstError: Can't rebind const(majic)


参考http://www.91code.cn/python/2013/0416/2664.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: