下面的python模块意味着在python中“常量”处理的基础。用例是:征求意见:python类工厂的恒定值组
与它们的值一起属于成字典- 一个基团的一些常量(基本上是“名称”)时间
- 这个类的属性是不变的名称,它们的值是常量本身
代码:
class ConstantError(Exception):
def __init__(self, msg):
self._msg = msg
class Constant(object):
def __init__(self, name):
self._name = name
def __get__(self, instance, owner):
return owner._content[self._name]
def __set__(self, instance, value):
raise ConstantError, 'Illegal use of constant'
def make_const(name, content):
class temp(object):
_content = content
def __init__(self):
for k in temp._content:
setattr(temp, k, Constant(k))
temp.__name__ = name + 'Constant'
return temp()
num_const = make_const('numeric', {
'one': 1,
'two': 2
})
str_const = make_const('string', {
'one': '1',
'two': '2'
})
用途:
>>> from const import *
>>> num_const
<const.numericConstant object at 0x7f03ca51d5d0>
>>> str_const
<const.stringConstant object at 0x7f03ca51d710>
>>> num_const.one
1
>>> str_const.two
'2'
>>> str_const.one = 'foo'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "const.py", line 16, in __set__
raise ConstantError, 'Illegal use of constant'
const.ConstantError
>>>
请评论的设计,实施和对应到Python编码准则。
+1你是正确的,在Python它常常可以归结为只是使用的类型的字典,元组和列表的正确组合,你就大功告成了。 – u0b34a0f6ae 2009-12-10 00:37:43
“您的设计似乎将一些其他语言功能带入python。” 这是故意的:-)基本上,我需要的东西足够接近C宏。想象一下带有“位域”参数的C函数,你想通过'ctypes'调用。那么有一些符号代替数字来代替它们是很好的。 – 2009-12-10 00:38:48
@ht:你必须意味着按位或Python中的'|'。注意sets和bitflags与'|'运算符的行为相同 - 所以在Python中,如果你喜欢,你可以实现那些组合标志作为整数或集合。 – u0b34a0f6ae 2009-12-10 00:50:36