下面的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